This reduce()
function applies the function of two arguments cumulatively to the items of iterable, from left to right, and then reduces the iterable to a single value.
reduce(function, iterable [, initializer])
Here,
>>> reduce(lambda x, y: x+y, [1, 2, 3, 4])
10 # ((1+2)+3)+4)
>>> reduce(lambda x, y: x-y, [125, 25, 5, 1])
94 # ((125-25)-5)-1)
>>> reduce(lambda x, y: x*y, [2, 2, 2, 2])
16 # ((2*2)*2)*2)
>>> reduce(lambda x, y: x/y, [125, 25, 5, 1])
1 # ((125/25)/5)/1)
>>> reduce(lambda x, y: x*y, [1])
1
Here, the left argument, x, is the accumulated value and the right argument, y, is the updated value from the iterable.
>>> reduce(lambda x, y: x+y, [], 1)
1
>>> reduce(lambda x, y: x+y, [], 0)
0
>>> reduce(lambda x, y: x*y, [1, 2, 3], 0)
0 # ((0*1)*2)*3)