< BACKMake Note | BookmarkCONTINUE >
156135250194107072078175030179198180024228156016206217188240240204174053205055217125088143

Built-in Functions: apply(), filter(), map(), reduce()

In this section, we will look at the apply(), filter(), map(), and reduce() built-in functions as well as give some examples to show how they can be used. These functions provide the functional programming features found in Python. A summary of these functions is given in Table 11.1. All take a function object to somehow invoke.

Table 11.1. Functional Programming Built-in Functions
Built-in Function Description
apply(func[, nkw][, kw]) call func with optional arguments, nkw for non-keyword arguments and kw for keyword arguments; the return value is the return value of the function call
filter(func, seq) invokes Boolean function func iteratively over each element of seq; returns a sequence for those elements for which func returned true
map(func, seq1[, seq2…]) applies function func to each element of given sequences(s) and provides return values in a list; if func is None, func behaves as the identity function, returning a list consisting of n- tuples for sets of elements of each sequence
reduce(func, seq[, init]) applies binary function func to elements of sequence seq, taking a pair at a time (previous result and next sequence item), continually applying the current result with the next value to obtain the succeeding result, finally reducing our sequence to a single return value; if initial value init given, first compare will be of init and first sequence element rather than the first two sequence elements

As you may imagine, lambda functions fit nicely into applications using any of these functions because all of them take a function object with which to execute, and lambda provides a mechanism for creating functions on the fly.


Last updated on 9/14/2001
Core Python Programming, © 2002 Prentice Hall PTR

< BACKMake Note | BookmarkCONTINUE >

© 2002, O'Reilly & Associates, Inc.