Introduction & Syntax
List Comprehensions · Study material
A list comprehension builds a new list from an iterable in one readable expression: [n * n for n in range(10) if n % 2 == 0]. It replaces the "create an empty list, loop, append" pattern, usually runs faster than that loop, and is one of the features that makes Python code look Pythonic. The same syntax gives dict, set and generator comprehensions. Tests focus on the details: where the if goes, the order of several for clauses, nested comprehensions and generators that run dry. This topic covers them all, then 50 practice questions run on Python 3.
On this page
- The basic form and its loop equivalent
- Filtering (if after for) vs choosing a value (if-else before for)
- Several for clauses and their order
- Nested comprehensions for matrices
- Dict, set and generator comprehensions
- Scope, the walrus operator and when to use a loop instead
The basic form
[expression for item in iterable] evaluates the expression for every item and collects the results into a new list. It is equivalent to an empty list plus a for loop with append – read it as "expression, for each item in iterable".
# The loop way …
squares = []
for n in range(1, 6):
squares.append(n * n)
# … and the comprehension: [expression for item in iterable]
squares2 = [n * n for n in range(1, 6)]
print(squares, squares == squares2)
names = ["asha", "ravi", "meera"]
print([name.title() for name in names])
print([len(name) for name in names])
print([c for c in "LearnFrenzy" if c.isupper()])
[1, 4, 9, 16, 25] True ['Asha', 'Ravi', 'Meera'] [4, 4, 5] ['L', 'F']
Filtering versus choosing a value
An if after the for clause is a filter: items that fail it are left out. A conditional expression a if cond else b before the for clause is part of the output expression: every item is kept, but its value depends on the condition. The filter form has no else; the conditional expression must have one.
marks = [72, 35, 88, 40, 19, 64]
# Filter: "if" AFTER the for – keeps only some items (the list can get shorter)
passed = [m for m in marks if m >= 40]
# Transform: "if … else" BEFORE the for – every item kept, the value chosen
labels = ["pass" if m >= 40 else "fail" for m in marks]
# Both at once
grace = [m + 5 if m >= 35 else m for m in marks if m > 30]
print(passed)
print(labels)
print(grace)
[72, 88, 40, 64] ['pass', 'fail', 'pass', 'pass', 'fail', 'pass'] [77, 40, 93, 45, 69]
Several for clauses
A comprehension may contain several for (and if) clauses. They nest from left to right, in the same order you would write the nested loops: the first for is the outer loop. That is why flattening is written [n for row in matrix for n in row].
# for clauses read left to right, exactly like nested for loops
pairs = [(x, y) for x in range(1, 4) for y in "ab"]
print(pairs)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [n for row in matrix for n in row] # outer loop FIRST
print(flat)
# Equivalent loops:
flat2 = []
for row in matrix:
for n in row:
flat2.append(n)
print(flat == flat2)
print([(a, b) for a in range(1, 5) for b in range(a, 5) if a + b == 5])
[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')] [1, 2, 3, 4, 5, 6, 7, 8, 9] True [(1, 4), (2, 3)]
Nested comprehensions
A comprehension can itself be the output expression of another comprehension, producing a list of lists – a table, a matrix, its transpose. Unlike [[0] * 3] * 3, this creates a separate inner list for every row.
# A comprehension INSIDE a comprehension builds a list of lists
table = [[r * c for c in range(1, 5)] for r in range(1, 4)]
for row in table:
print(row)
m = [[1, 2, 3], [4, 5, 6]]
transpose = [[row[i] for row in m] for i in range(len(m[0]))]
identity = [[1 if r == c else 0 for c in range(3)] for r in range(3)]
print(transpose)
print(identity)
[1, 2, 3, 4] [2, 4, 6, 8] [3, 6, 9, 12] [[1, 4], [2, 5], [3, 6]] [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
Dict, set and generator comprehensions
{k: v for …} builds a dict, {x for …} a set and (x for …) a generator expression. A generator expression produces values lazily, one at a time, so it uses almost no memory – ideal inside sum(), max(), any(), all() and "".join(), where the brackets of the call are enough.
words = ["apple", "kiwi", "banana", "fig", "kiwi"]
lengths = {w: len(w) for w in words} # dict comprehension
first_letters = sorted({w[0] for w in words}) # set comprehension (sorted for a fixed order)
total = sum(len(w) for w in words) # generator expression: no list built
print(lengths)
print(first_letters, total)
prices = {"tea": 20, "coffee": 35, "juice": 60}
print({k: v * 2 for k, v in prices.items() if v < 50})
{'apple': 5, 'kiwi': 4, 'banana': 6, 'fig': 3}
['a', 'b', 'f', 'k'] 22
{'tea': 40, 'coffee': 70}Generator expressions are lazy and single-use
A generator computes each value only when asked (by next(), a for loop or a function such as sum) and can be iterated once. After that it is exhausted and yields nothing. Store the results in a list if you need them twice. Generators have no len() and cannot be indexed.
gen = (n * n for n in range(5)) # round brackets: a lazy generator
print(type(gen).__name__)
print(next(gen), next(gen)) # values are produced on demand
print(list(gen)) # the rest …
print(list(gen)) # … and then it is exhausted
big = sum(n for n in range(1_000_001) if n % 7 == 0) # never stores a million numbers
print(big)
print(any(n > 100 for n in [5, 50, 500]), all(n % 2 == 0 for n in [2, 4, 7]))
generator 0 1 [4, 9, 16] [] 71428928571 True False
Scope and the walrus operator
In Python 3 the loop variable of a comprehension is local to it and does not overwrite a variable of the same name outside. The walrus operator := can compute a value once and use it in both the filter and the output; a name bound with := does stay visible after the comprehension.
x = "outer"
squares = [x * x for x in range(4)] # x here is local to the comprehension
print(x, squares) # the outer x is untouched (Python 3)
readings = [3, 12, 7, 25, 9]
# := computes a value once and reuses it in the filter and the output
big = [scaled for r in readings if (scaled := r * 10) > 80]
print(big)
outer [0, 1, 4, 9] [120, 250, 90]
Common mistakes
- [x for x in a if c else y] – a filter cannot have else; move the if-else in front of for.
- Writing the for clauses in the wrong order – the outer loop comes first.
- Reusing a generator – the second pass is empty.
- len() of a generator – TypeError; use a list or sum(1 for …).
- Comprehensions for side effects – [print(x) for x in a] builds a useless list of None; use a for loop.
- Cramming too much in – three nested clauses with conditions are hard to read; use a loop or a helper function.
Key points to remember
- [expr for x in it if cond] – the if after for filters.
- [a if c else b for x in it] – the if-else before for chooses values.
- Multiple for clauses nest left to right, outer first.
- {k: v …} dict, {x …} set, (x …) generator.
- Generators are lazy and can be used only once.
- Comprehension variables do not leak into the surrounding scope.
- Use a comprehension to build a collection, a loop for side effects.
Frequently asked questions
Are list comprehensions faster than for loops?
Usually somewhat, because the append happens inside the interpreter without a method lookup each time. Readability is the main reason to use them.
Is there a tuple comprehension?
No. (x for x in it) is a generator expression; use tuple(x for x in it) to build a tuple.
When should I use a generator instead of a list?
When the values are consumed once, in order – sum(), any(), writing to a file – especially for large data. Use a list when you need indexing, len() or several passes.
Where can I learn more?
Read Python List Comprehensions and Python Generators in the Python tutorial, then practise with the exercises below.