Comprehensions
Build lists, sets, and dicts from other collections — concisely and Pythonically.
- Read and write list, set, and dict comprehensions
- Add filtering with an if clause
- Recognise when a comprehension helps clarity — and when a loop is clearer
A comprehension builds a new collection by transforming and filtering an existing one, in a single readable expression. It's one of the most characteristically Pythonic tools — powerful when used with restraint, a readability hazard when overused.
From loop to comprehension
This loop:
squares = []
for n in range(10):
squares.append(n * n)becomes:
squares = [n * n for n in range(10)]Read it left to right: the value to collect (n * n), then where it comes
from (for n in range(10)). Same result, one line, and the intent — "a list of
squares" — is right there at the front.
Adding a filter
Append an if to keep only some items:
evens = [n for n in range(10) if n % 2 == 0] # [0, 2, 4, 6, 8]Set and dict comprehensions
The same shape builds sets and dicts — just change the brackets:
unique_lengths = {len(word) for word in words} # a set
name_to_len = {word: len(word) for word in words} # a dictGenerator expressions
Swap the brackets for parentheses and you get a generator — it produces items one at a time instead of building the whole collection in memory. Ideal for large data or when you only need to iterate once:
total = sum(n * n for n in range(1_000_000)) # no giant list is ever storedThis is the data-structures and complexity lessons showing up in syntax: choosing a generator over a list is choosing O(1) space over O(n).
Comprehensions reward simple transforms. If you find yourself nesting two or three, or stuffing complex logic inside, switch back to a plain loop. Clever one-liners that nobody can read are a net loss — clarity beats cleverness.
Where to go next
Comprehensions are a gateway to Python's functional style. From here, explore the rest of the intermediate track, or jump to JavaScript / TS to see how another language handles the same ideas.