Reputation: 21
I came across this code when I was researching how the reduce()
function in Python works. It prints 7
, which is the expected output, and returns the total number of items from list1
, the same as that of len(list1)
. I am interested to know how this code works.
0
in the reduce do?x = list1
and y = 0
? In that case, why does x + y
return the sum of all values (28
) in the list? from functools import reduce
list1 = [1 ,2, 3, 4, 5, 6, 7]
count = reduce(lambda x, y : x + 1, list1, 0)
print(count)
Output: 7
Upvotes: 2
Views: 10487
Reputation: 3829
The reduce function is quite well documented
As the documentation states:
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
Essentially calculates ((((1+2)+3)+4)+5)
, where x
is the previous result (default zero) and y
is the next value in the list.
The zero in your example acts as an initial value, so:
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5], 0)
Calculates (((((0+1)+2)+3)+4)+5)
In your example, y
is not used, so
reduce(lambda x, y : x + 1, list1, 0)
is the equivalent of (0+1)+1)+1)+1)+1)+1)+1)
so you get the answer 7
Upvotes: 5
Reputation: 504
the 0 is the initial value to be passed to the function supplied to reduce()
, in yout case - lambda x, y: x+1
.
reduce()
takes the first and second elements in the list passed to it and passes them to the lambda
function. then, reduce()
takes the output of this function and feeds it back to it along with the third element in the list. this process continues until all the values in the list pass through the function.
lambda x, y: x+1
just means "take two numbers as parameters (x and y) and return the first one plus 1.
since the first value to be passes as x
is 0 (it is the initial value supplied to reduce()
), lambda
will just increase it by 1 for every element in the list
Upvotes: 1