1

I wrote a piece python code like this

import random

val_hist = []
for i in range(100):
    val_hist.append(random.randint(0,1000))


def print__(x):
    print type(x[1])
map(lambda x: print__(x), list(enumerate(val_hist)))

l_tmp = list(enumerate(val_hist))
idx_list = map(lambda x: x[0], l_tmp)
val_list = map(lambda x: x[1], l_tmp)

print idx_list
print val_list

reduce(lambda sum, x: sum + x[1], list(enumerate(val_hist)))
print reduce(lambda sum, x: sum + x, val_hist)
print reduce(lambda sum, x: sum + x[1], list(enumerate(val_hist)))

When I ran this code, I got this error "TypeError: can only concatenate tuple (not "int") to tuple". Does anyone know how this happened? Or does anyone know how python function reduce works exactly?

1
  • Have you tried reading the documentation? Commented Jul 22, 2016 at 7:55

1 Answer 1

2

You need to provide a third argument to reduce, which is the initializer. From the docs:

If initializer is not given and iterable contains only one item, the first item is returned.

Since you aren't explicitly providing an initializer parameter, reduce is using the first element from list(enumerate(val_hist)), which happens to be a tuple. You're trying to add this tuple together with x[1] which is an integer.

So, simply update your reduce with an initializer value of 0, like so:

>>> reduce(lambda sum, x: sum + x[1], list(enumerate(val_hist)), 0)
>>> 48279
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, it makes sense. Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.