Skip to content

Comprehensions

A comprehension is a concise, readable expression that builds a new collection by transforming or filtering an iterable. Python provides three forms: list, dict, and set comprehensions.

The general form is:

[expression for item in iterable]
[expression for item in iterable if condition]
squares = [x**2 for x in range(1, 8)]
# [1, 4, 9, 16, 25, 36, 49]
evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Both examples are equivalent to a for loop that appends to a list — but they are more compact and typically faster because the iteration happens in C rather than bytecode.

You can nest multiple for clauses to iterate over combinations. The clauses are read left to right — the leftmost for is the outer loop.

pairs = [
(x, y)
for x in range(1, 4)
for y in range(1, 4)
if x != y
]
# [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

Wrap the expression in {} and use key: value syntax.

word_len = {word: len(word) for word in ['apple', 'banana', 'cherry']}
# {'apple': 5, 'banana': 6, 'cherry': 6}

Dict comprehensions are a clean way to invert a mapping, filter entries, or transform values:

prices = {'apple': 1.5, 'banana': 0.75, 'cherry': 3.0}
expensive = {k: v for k, v in prices.items() if v >= 1.5}
# {'apple': 1.5, 'cherry': 3.0}

Same syntax as list comprehensions but with {}. Duplicates are automatically discarded.

unique_lens = {len(word) for word in ['apple', 'banana', 'cherry', 'date']}
# {4, 5, 6} (order not guaranteed)
# --- list comprehension ---
squares = [x**2 for x in range(1, 8)]
print('squares:', squares)
evens = [x for x in range(20) if x % 2 == 0]
print('evens:', evens)
# --- nested comprehension ---
pairs = [(x, y) for x in range(1, 4) for y in range(1, 4) if x != y]
print('pairs:', pairs)
# --- dict comprehension ---
word_len = {word: len(word) for word in ['apple', 'banana', 'cherry']}
print('word lengths:', word_len)
# --- set comprehension ---
unique_lens = {len(word) for word in ['apple', 'banana', 'cherry', 'date']}
print('unique lengths:', sorted(unique_lens))
What does `[x**2 for x in range(4)]` produce?
How do you add a filter to a list comprehension?
Which comprehension type automatically removes duplicates?
In `[f(x, y) for x in A for y in B]`, which loop is the OUTER loop?