预计阅读本页时间:-
List Comprehensions Revisited: Functional Tools
In the prior chapter, we studied functional programming tools like map and filter, which map operations over sequences and collect results. Because this is such a common task in Python coding, Python eventually sprouted a new expression—the list comprehension—that is even more flexible than the tools we just studied. In short, list comprehensions apply an arbitrary expression to items in an iterable, rather than applying a function. As such, they can be more general tools.
We met list comprehensions in Chapter 14, in conjunction with looping statements. Because they’re also related to functional programming tools like the map and filter calls, though, we’ll resurrect the topic here for one last look. Technically, this feature is not tied to functions—as we’ll see, list comprehensions can be a more general tool than map and filter—but it is sometimes best understood by analogy to function-based alternatives.