Next / Previous / Contents / Shipman's homepage

20.35. reduce(): Sequence reduction

The idea of reduction comes from the world of functional programming. There is a good introductory article on this concept in Wikipedia. In simple terms, a function of two arguments is applied repeatedly to the elements of an iterable to build up a final value.

There are two general forms:

reduce(f, S)
reduce(f, S, I)

The result depends on the number of elements in S, and whether the initial value I is supplied. Let's look first at the case where argument I is not supplied.

If an initial value I is provided, the result is the same as reduce(f, [I]+list(S)).

Some examples:

>>> def x100y(x,y):
...     return x*100+y
>>> reduce(x100y, [15])
>>> reduce(x100y, [1,2])
>>> reduce(x100y, [1,2,3])
>>> reduce(x100y, (), 44)
>>> reduce(x100y, [1], 2)
>>> reduce(x100y, [1,2], 3)
>>> reduce(x100y, [1,2,3], 4)
>>> reduce(x100y, [])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: reduce() of empty sequence with no initial value