-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating
Python Essentials
By :
A function which accepts a function as an argument, or returns a function as a result, is called a higher-order function. Python has a number of higher-order functions. The most commonly-used of these functions are map(), filter(), and sorted(). The itertools module contains numerous additional higher-order functions.
The map() and filter() functions are generators; their results must be consumed. Both of them apply a function to a collection of values. In the case of map(), the results of the function are yielded. In the case of filter(), if the result of the function is true, the original value is yielded.
Here's how we can apply a very simple function—so simple we coded it as a lambda—to a sequence of values:
>>> mapping= map( lambda x: 2*x**2-2, range(5) ) >>> list(mapping) [-2, 0, 6, 16, 30]
The function is just an expression, 2*x**2-2. We've applied this function to values given by the range() object. The result is a generator, and we...