A comprehension is a compact syntactic construct for building a new collection by transforming and/or filtering an existing iterable. Python supports four forms: list comprehensions ([expr for x in iterable]), set comprehensions ({expr for x in iterable}), dictionary comprehensions ({k: v for k, v in iterable}), and generator expressions ((expr for x in iterable)). All four support optional if clauses for filtering and multiple for clauses for nested iteration.
Comprehensions are one of Python's most distinctive and beloved features. They replace the common pattern of initialising an empty collection, writing a for loop, and appending to it — all in a single readable expression. For example, [x**2 for x in range(10) if x % 2 == 0] creates a list of the squares of even numbers from 0 to 9. Comprehensions are not only more concise but often faster than equivalent loops, because the iteration happens in optimised C code inside CPython.
A common guideline is to keep comprehensions simple: if a comprehension requires more than two levels of nesting or complex conditions, a regular loop is more readable. Generator expressions are particularly useful for large datasets because they produce items lazily, one at a time, without building the entire collection in memory.
Related terms: List, Set, Dictionary, Generator Expression
Discussed in:
- Chapter 6: Data Structures — List Comprehensions