There are three built-in functions that are very useful when used with
lists: filter()
, map()
, and reduce()
.
filter(function, sequence)
returns a sequence (of the same
type, if possible) consisting of those items from the sequence for
which function(item)
is true. For example, to compute some
primes:
>>> def f(x): return x%2 != 0 and x%3 != 0 ... >>> filter(f, range(2, 25)) [5, 7, 11, 13, 17, 19, 23] >>>
map(function, sequence)
calls function(item)
for each of
the sequence's items and returns a list of the return values. For
example, to compute some cubes:
>>> def cube(x): return x*x*x ... >>> map(cube, range(1, 11)) [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] >>>
More than one sequence may be passed; the function must then have as
many arguments as there are sequences and is called with the
corresponding item from each sequence (or None
if some sequence
is shorter than another). If None
is passed for the function,
a function returning its argument(s) is substituted.
Combining these two special cases, we see that
map(None, list1, list2)
is a convenient way of turning a pair
of lists into a list of pairs. For example:
>>> seq = range(8) >>> def square(x): return x*x ... >>> map(None, seq, map(square, seq)) [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)] >>>
reduce(func, sequence)
returns a single value constructed
by calling the binary function func
on the first two items of the
sequence, then on the result and the next item, and so on. For
example, to compute the sum of the numbers 1 through 10:
>>> def add(x,y): return x+y ... >>> reduce(add, range(1, 11)) 55 >>>
If there's only one item in the sequence, its value is returned; if the sequence is empty, an exception is raised.
A third argument can be passed to indicate the starting value. In this case the starting value is returned for an empty sequence, and the function is first applied to the starting value and the first sequence item, then to the result and the next item, and so on. For example,
>>> def sum(seq): ... def add(x,y): return x+y ... return reduce(add, seq, 0) ... >>> sum(range(1, 11)) 55 >>> sum([]) 0 >>>