Python Tutorial Was: Guido's regrets: filter and map

Anders J. Munch andersjm at dancontrol.dk
Tue Nov 26 05:10:47 EST 2002


"Terry Hancock" <hancock at anansispaceworks.com> wrote:
>(BTW, I never used
> reduce, never understood what it was good for, and don't immediately
> see how it can be done using list-comps -- would be genuinely interested
> in seeing a couple of example if anyone's willing). 

from operator import add
reduce(add, [1, 3, 17])

More generally, reduce is (true) functional programmings answer to for
loops.  A for loop on the general form:

S = initial_s
for x in xs:
    S = change(S,x)
# result in S

can be expressed functionally as:

reduce(change, xs, initial_S)

my-only-beef-with-reduce-is-that-I-can-never-remember-what-it's-called-ly
y'rs, Anders





More information about the Python-list mailing list