Tyler Tyler - 29 days ago 14
Python Question

TypeError: Reduce() of empty sequence with no initial value

I'm currently trying to write a function that will give me a tuple whose 0 index is the amount of lines in that file, and whose 1 index is how many characters are in that file. So far, I have a list of tuples, which looks like this:

mapped = [(1, 50), (1, 11), (1, 58)]


The line I'm trying to write is this:

reduce(lambda x:(x[0]+y[0], x[1]+y[1]),(i for i in mapped))


If it works correctly, then it should return a tuple of (3, 119). However, I'm getting an error of

TypeError: reduce() of empty sequence with no initial value


Can anybody figure out why this is?

Answer

Use this way:

>>> reduce(lambda x,y:(x[0]+y[0], x[1]+y[1]),[i for i in mapped])
(3, 119)
>>> reduce(lambda x,y:(x[0]+y[0], x[1]+y[1]),(i for i in mapped))
(3, 119)

What you miss is that lambda should take two parameters, you just give one.

For Python3.x see the code below:

>>> from functools import reduce
>>> reduce(lambda x:(x[0]+y[0], x[1]+y[1]),(i for i in mapped))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: <lambda>() takes exactly 1 positional argument (2 given)
>>> reduce(lambda x,y:(x[0]+y[0], x[1]+y[1]),(i for i in mapped))
(3, 119)