Nested comprehension
- Python course
- Beginner
- Lesson 62/116
- 4 min
Learn nested comprehensions.
Nested comprehension
A comprehension can contain multiple for clauses. This corresponds to nested loops:
pairs = [(a, b) for a in [1, 2] for b in [3, 4]]
# [(1, 3), (1, 4), (2, 3), (2, 4)]The first for is the outer loop, the second for is the inner loop. The result lists each (a, b) pair in order.
When a nested comprehension grows complex, readability suffers; then a classic loop may be better.
Flatten a matrix
A nested comprehension is handy for flattening a matrix into a single list:
matrix = [[1, 2], [3, 4]]
flat = [n for row in matrix for n in row]
# [1, 2, 3, 4]First row is taken from the matrix, then n is taken from that row. This is a very short form.
Practice Build a multiplication table
Assign to products a nested comprehension that computes a * b for every pair of a in [1, 2] and b in [3, 4]. Then print print(products).
Starter code
# Products with a nested comprehensionSample solution
products = [a * b for a in [1, 2] for b in [3, 4]]
print(products)Expected output
[3, 4, 6, 8]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the nested parts
| Term | Meaning |
|---|---|
for a in [1, 2] |
Outer loop |
for b in [3, 4] |
Inner loop |
(a, b) |
Expression |
[...] |
Result list |
2 Complete the nested comprehension
flat = [n for row in matrix for ____ in row]
flat = [n for row in matrix for n in row]
Explanation: The inner loop takes n from row.
3 What does [(a, b) for a in [1, 2] for b in [3]] produce?
- [(1, 3)]
- [(2, 3)]
- [(1, 3), (1, 4), (2, 3), (2, 4)]
- [(1, 3), (2, 3)] Correct answer
Explanation: Pairs (1,3) and (2,3) are produced.