Dry_accountant_09
Dry_accountant_09

Reputation: 1499

Reduce function fails with three parameters and runs fine with two parameters in python

from functools import reduce
o = [20,30,100,60,80,90]

#1 
print(reduce((lambda x,y:x+y),o)) # returns 380
#2
print(reduce((lambda x,y,z:x+y+z),o)) # FAILS
#3
print(reduce((lambda x,y,z=10:x+y+z),o)) # returns 430 

Can someone explain why the #1 is working fine and #2 fails.

Upvotes: 0

Views: 44

Answers (1)

Selcuk
Selcuk

Reputation: 59184

From the documentation:

Apply function of two arguments cumulatively to the items of iterable [...]

This means that the function should accept 2 arguments, not 3. If you think of it, the third argument does not make any sense. The first argument is the previously reduced value and the second argument is the next value.

In your third example the third argument is optional, so it still works when it is passed only 2 arguments.

Upvotes: 1

Related Questions