Next / Previous / Contents / TCC Help System / NM Tech homepage

13.30. reduce(): Sequence reduction

This function is used to apply some two-argument function f(x, y) pairwise to each pair of the elements of a sequence S in turn, with an optional initial value I. Here are the 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])
15
>>> reduce(x100y, [1,2])
102
>>> reduce(x100y, [1,2,3])
10203
>>> reduce(x100y, (), 44)
44
>>> reduce(x100y, [1], 2)
201
>>> reduce(x100y, [1,2], 3)
30102
>>> reduce(x100y, [1,2,3], 4)
4010203