Question

I'm relatively new to Python and am having trouble
with Folds or more specifically, reduce()'s 'initializer' argument

e.g. reduce(function, iterable[, initializer])

Here is the function...

>>> def x100y(x,y):
...     return x*100+y

Could someone explain why reduce() produces 44...

>>> reduce(x100y, (), 44)
44

or why it produces 30102 here...

>>> reduce(x100y, [1,2], 3)
30102
Was it helpful?

Solution

From the docs:

reduce(function, iterable[, initializer])

Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable. If the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If initializer is not given and iterable contains only one item, the first item is returned.

The initializer is placed as element 0 in your iterable and if there are no elements in your iterable it is returned. (So this is why you get 44)

Also, x100y is not a valid python function. If you want to make it into a valid python function you would have to do

reduce(lambda x,y: x*100*y,[1,2],3)

which is equivalent to

(3*100*1)*100*2 which should give 60000 (why you got the value you had is probably because of an error)

Documentation on lambda is here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top