Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 718
Tyler Avatar asked Feb 11 '15 06:02

Tyler


3 Answers

Nobody answer why there is an error: TypeError: reduce() of empty sequence with no initial value

When the list literal which is second parameter is empty, the error occurs. So if you try reduce(lambda x, y:(x[0]+y[0], x[1]+y[1]), [])

You'll get the error.

like image 88
Jacob CUI Avatar answered Nov 15 '22 23:11

Jacob CUI


map(sum, ...) fits better, looks beautiful.

map(sum, zip(*mapped))

You can use itertools.izip_longest if lengths of the lists are different.

like image 36
Ozgur Vatansever Avatar answered Nov 15 '22 22:11

Ozgur Vatansever


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)
like image 4
lqhcpsgbl Avatar answered Nov 15 '22 22:11

lqhcpsgbl