Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<lambda>() missing 1 required positional argument: 'z' with lambda and reduce

I was trying to understand how lambda and reduce() works. I tried these examples but not able to understand why this is giving me the error. Can someone please explain how it is being executed?

>>> functools.reduce(lambda x,y:x+y, range(10))
45

This works fine. But when I tried this, It gives me error:

>>> functools.reduce(lambda x,y,z:x+y+z, range(10))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: <lambda>() missing 1 required positional argument: 'z'
like image 703
Shibasis Patel Avatar asked Mar 13 '26 04:03

Shibasis Patel


1 Answers

functools.reduce requires a function of two arguments. You cannot pass a lambda x, y, z as the function because that's a function of 3 arguments. (In Python it's an error to call a function with incorrect number of arguments. functools.reduce would call the lambda x, y, z with only 2 arguments instead of 3, and so that's an error.)

From help(functools.reduce):

reduce(...)
    reduce(function, sequence[, initial]) -> value

    Apply a function of two arguments cumulatively to the items of a sequence,
    from left to right, so as to reduce the sequence to a single value.
    For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
    ((((1+2)+3)+4)+5).
like image 144
janos Avatar answered Mar 15 '26 23:03

janos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!