A higher-order function is a function that accepts another function as an argument or returns a function. The examples here focus on functions such as map() and filter(), which receive a function and apply it to iterable values. section 8.3.2 section 14.3.1
Use higher-order functions to separate an operation from the iterable it processes:
- map() applies a named function or lambda to every element and produces a lazy result; use list() when immediate values are needed. section 8.3.2
- filter() applies a predicate to every element and keeps only values whose result is truthy. section 14.3.1
- Compare these forms with list comprehensions: map() expresses transformation, while filter() corresponds to a comprehension guard. section 14.3.1
- Pass new_char rather than new_char() when supplying a function; the parentheses would call it immediately instead of passing it. section 8.3.2
Transform every character with map()
>>> list(map(lambda car: 'blue ' + car, ['BMW', 'Alfa Romeo', 'Chrysler'])) ['blue BMW', 'blue Alfa Romeo', 'blue Chrysler'] A named function works the same way: def add1(n): return n + 1 >>> list(map(add1, [1, 2, 3])) [2, 3, 4] section 8.3.2
Keep only matching values with filter()
>>> cars = ['blue Honda', 'red Chevy', 'blue Ford'] >>> list(filter(lambda car: car.startswith('blue '), cars)) ['blue Honda', 'blue Ford'] The same pattern can select consonants by retaining characters for which c not in vowels is truthy. section 14.3.1
>>> list(map(lambda car: 'blue ' + car, ['BMW', 'Alfa Romeo', 'Chrysler'])) ['blue BMW', 'blue Alfa Romeo', 'blue Chrysler']
Run a compact map() example that makes the function argument and transformed output visible immediately. section 8.3.2













