Sub topic 10
Building lists with comprehensions
This chapter assumes you can write for loops and if statements, call methods such as append, and read a basic function call. It also assumes you know that a list is a mutable sequence. It builds on iteration and does not repeat how loops work.
The working model
A list comprehension is an expression that builds a new list from any iterable. The basic form has three parts: an expression, a for clause, and an optional if clause.
squares = []
for n in range(6):
if n % 2 == 0:
squares.append(n * n)
print(squares) # [0, 4, 16]
squares = [n * n for n in range(6) if n % 2 == 0]
print(squares) # [0, 4, 16]Both versions give the same result. Read the comprehension in this order: the for clause supplies each item, the if clause decides whether to keep it, and the leading expression computes what goes into the new list.
The next diagram shows what happens for each item.
Filtering and transforming
Use the trailing if to drop items. Use the leading expression to change items. You can do both at once.
words = ["Pear", "fig", "Banana", "kiwi"]
short = [w.lower() for w in words if len(w) <= 4]
print(short) # ['pear', 'fig', 'kiwi']
raw = ["3", "x", "7"]
nums = [int(s) for s in raw if s.isdigit()]
print(nums) # [3, 7]The filter runs before the expression. In the second example, int(s) is never called on "x", so no ValueError occurs.
Where if and else go
A trailing if filters and cannot have an else. If you want every item to produce a value, put a conditional expression (a if cond else b) in the leading expression.
labels = ["even" if n % 2 == 0 else "odd" for n in range(4)]
print(labels) # ['even', 'odd', 'even', 'odd']
clamped = [x if x > 0 else 0 for x in [-1, 2, -3]]
print(clamped) # [0, 2, 0]Adding else after the trailing filter is a SyntaxError:
# [n for n in range(4) if n % 2 == 0 else 0] # SyntaxErrorYou can combine both forms. The conditional expression decides the value, and the trailing if decides whether the item is kept at all.
| Goal | Shape |
|---|---|
| Keep only some items | `[f(x) for x in it if cond(x)]` |
| Change every item, two outcomes | `[a if cond(x) else b for x in it]` |
| Both | `[a if cond(x) else b for x in it if keep(x)]` |
Several for clauses
A comprehension can have more than one for clause. The clauses nest in the same order you would write them as loops, with the first clause as the outermost loop.
pairs = [(x, y) for x in range(3) for y in range(x)]
print(pairs) # [(1, 0), (2, 0), (2, 1)]
matrix = [[1, 2, 3], [4, 5, 6]]
flat = [v for row in matrix for v in row]
print(flat) # [1, 2, 3, 4, 5, 6]For flat, the equivalent loops are for row in matrix: and then for v in row:. The order reads the same as the nested loops, even though the expression comes first.
You can also put a comprehension inside the expression part to build a nested list. This is the safe way to create a grid, because each row is a separate list.
grid = [[0] * 3 for _ in range(2)]
grid[0][0] = 1
print(grid) # [[1, 0, 0], [0, 0, 0]]
transposed = [[row[i] for row in matrix] for i in range(3)]
print(transposed) # [[1, 4], [2, 5], [3, 6]]The inner expression [0] * 3 runs again for every row, so each row is a fresh list. The pattern [[0] * 3] * 2 runs it once and repeats the reference to that single list.
Scope and evaluation rules
A comprehension has its own scope in Python 3. The loop variable does not leak into the surrounding code.
x = "outer"
doubled = [x * 2 for x in range(3)]
print(doubled) # [0, 2, 4]
print(x) # outerThe expression is evaluated when the comprehension runs, but names inside a lambda are looked up later, when the lambda is called. That produces a classic surprise:
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs]) # [2, 2, 2]
fixed = [lambda i=i: i for i in range(3)]
print([f() for f in fixed]) # [0, 1, 2]All three lambdas in funcs refer to the same variable i. By the time you call them, i is 2. The default argument i=i captures the current value at creation time.
Comprehension, map and filter, or loop
All three can build the same list. Choose by readability.
nums = [1, 2, 3, 4, 5, 6]
by_comprehension = [n * 10 for n in nums if n % 2 == 0]
by_map_filter = list(map(lambda n: n * 10, filter(lambda n: n % 2 == 0, nums)))
print(by_comprehension) # [20, 40, 60]
print(by_map_filter) # [20, 40, 60]The comprehension is shorter and avoids the two lambdas. map is still reasonable when you already have a named function, as in list(map(str, nums)). A plain loop is better when the body needs several statements, try/except, or early exit with break. A comprehension holds one expression and cannot do those things.
A rough guide:
- Use a comprehension when you build one list from one iterable with at most one filter.
- Use a loop when the logic needs statements, multiple outputs, or error handling.
- Stop at two
forclauses. A third usually means a loop would be clearer.
Common errors
Using a comprehension for side effects
A comprehension builds a list. If you only want the side effect, you create a list you immediately throw away.
items = ["a", "b"]
# Avoid: builds [None, None] and discards it
[print(s) for s in items]
# Prefer
for s in items:
print(s)Building a large list you only consume once
A list comprehension creates every item in memory before the next step starts. If you only need to loop over the results once, or feed them to sum, any, all, min or max, use a generator expression. It has the same syntax with parentheses and produces items one at a time.
total = sum(n * n for n in range(1_000_000))
print(total) # 333332833333500000Use a list when you need indexing, len, or several passes over the data. A generator is exhausted after one pass.
Over-packing the expression
A comprehension with a nested conditional, two for clauses and a function call on each line is hard to read and hard to debug. Split it into a helper function or a loop. Short code that is easy to check beats short code that is clever.
Expecting in-place change
Because a comprehension creates a new list, assigning it to a name does not modify other references to the old list.
a = [1, 2, 3]
b = a
a = [n * 2 for n in a]
print(a) # [2, 4, 6]
print(b) # [1, 2, 3] (b still points at the old list)If other code holds a reference to the original list and must see the change, use slice assignment: a[:] = [n * 2 for n in a].
Exercise
Write one list comprehension that takes words = ["tree", "sky", "mountain", "sea"] and returns the uppercase version of only the words longer than 3 characters. What does it return?
Show answer
[w.upper() for w in words if len(w) > 3] returns ['TREE', 'MOUNTAIN']. The trailing if filters out "sky" and "sea" before upper() is applied.
Exercise
What does [x if x > 0 else 0 for x in [-1, 2, -3]] return, and why does [x for x in [-1, 2, -3] if x > 0 else 0] fail?
Show answer
The first returns [0, 2, 0], because the conditional expression yields a value for every item. The second is a SyntaxError, because a trailing if is a filter and cannot take an else.
Exercise
You run rows = [[0] * 3] * 2 and then rows[0][0] = 1. Rewrite the first line with a comprehension so that only the first row changes.
Show answer
Use rows = [[0] * 3 for _ in range(2)]. The inner list is created once per row, so rows[0][0] = 1 gives [[1, 0, 0], [0, 0, 0]].