5.7 Writing higher-order mappings and filters
Python’s two built-in higher-order functions, map()
and filter()
, generally handle almost everything we might want to throw at them. It’s difficult to optimize them in a general way to achieve higher performance. We’ll look at similar functions such as imap()
in Chapter 14, The Multiprocessing, Threading, and Concurrent.Futures Modules.
We have three largely equivalent ways to express a mapping. Assume that we have some function, f(x)
, and some collection of objects, C
. The ways we can compute a mapping from the domain value in C to a range value are as follows:
The
map()
function:map(f, C)
A generator expression:
(f(x) for x in C)
A generator function with a
yield
statement:from collections.abc import Callable, Iterable, Iterator from typing import Any def mymap(f: Callable[[Any], Any], C: Iterable[Any]) -> Iterator[Any]: for x in C: ...