- publishing free software manuals
An Introduction to Python
by Guido van Rossum and Fred L. Drake, Jr.
Paperback (6"x9"), 124 pages
ISBN 0954161769
RRP £12.95 ($19.95)

Sales of this book support the Python Software Foundation! Get a printed copy>>>

5.1.3 Functional Programming Tools

There are three built-in functions that are very useful when used with lists: filter(), map(), and reduce().

‘filter(function, sequence)’ returns a sequence consisting of those items from the sequence for which function(item) is true. If sequence is a string or tuple, the result will be of the same type; otherwise, it is always a list. 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 items in the sequence 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). For example:

    >>> seq = range(8)
    >>> def add(x, y): return x+y
    ...
    >>> map(add, seq, seq)
    [0, 2, 4, 6, 8, 10, 12, 14]

‘reduce(function, sequence)’ returns a single value constructed by calling the binary function function 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

Don't use this example's definition of sum(): since summing numbers is such a common need, a built-in function sum(sequence) is already provided, and works exactly like this. (Added in Python version 2.3)

ISBN 0954161769An Introduction to PythonSee the print edition