Sub topic 7
Multiple for clauses and flattening nested data
This chapter assumes you can write a basic list comprehension with an if filter, and that you know how nested for loops work. You will learn how a comprehension with several for clauses maps onto nested loops, and how to use that to flatten nested data.
Reading clauses in loop order
A comprehension can contain more than one for clause. The clauses are read left to right in the same order as the equivalent nested loops. The first for is the outer loop, and each later for is nested inside the one before it. The output expression stays at the front.
matrix = [[1, 2, 3], [4, 5, 6]]
# Nested loops
flat = []
for row in matrix:
for value in row:
flat.append(value)
# Same result as a comprehension
flat = [value for row in matrix for value in row]
print(flat) # [1, 2, 3, 4, 5, 6]The order trips up many readers because the output expression value comes first, but it is the last name to be defined. To check your ordering, write the nested loops on paper, then move the body to the front and keep the for lines in the same order.
Adding a filter
An if clause can follow any for clause. It is checked each time the loop above it produces a value, and it can use every name defined before it.
pairs = [(x, y) for x in range(3) for y in range(3) if x < y]
print(pairs) # [(0, 1), (0, 2), (1, 2)]The equivalent loops are:
pairs = []
for x in range(3):
for y in range(3):
if x < y:
pairs.append((x, y))
print(pairs) # [(0, 1), (0, 2), (1, 2)]You can also filter the outer loop to skip whole groups early, which avoids work in the inner loop.
matrix = [[1, 2, 3], [], [4, 5, 6]]
flat_odds = [v for row in matrix if row for v in row if v % 2 == 1]
print(flat_odds) # [1, 3, 5]Here if row skips empty rows, and if v % 2 == 1 keeps only odd values. Because each if sits right after the for it guards, the line reads in loop order.
A common error: reversing the order
Writing the clauses in the wrong order usually raises a NameError, because the inner clause uses a name that has not been defined yet.
matrix = [[1, 2, 3], [4, 5, 6]]
# Wrong: 'row' is used before the clause that defines it
# flat = [value for value in row for row in matrix] # NameError: name 'row' is not defined
# Right
flat = [value for row in matrix for value in row]
print(flat) # [1, 2, 3, 4, 5, 6]If the names happen to exist from earlier code, the wrong order does not fail. It silently produces a different list. Check the order whenever a result looks odd.
Nested comprehensions versus multiple clauses
Multiple for clauses produce one flat list. If you want to keep the structure, put a comprehension inside the output expression. This builds a list of lists.
matrix = [[1, 2, 3], [4, 5, 6]]
doubled_rows = [[v * 2 for v in row] for row in matrix]
print(doubled_rows) # [[2, 4, 6], [8, 10, 12]]
doubled_flat = [v * 2 for row in matrix for v in row]
print(doubled_flat) # [2, 4, 6, 8, 10, 12]| Form | Result shape | Use it when |
|---|---|---|
| `[v for row in m for v in row]` | One flat list | You want every item in a single sequence |
| `[[v for v in row] for row in m]` | List of lists | You want to keep the row structure |
Multiple clauses work for dict and set comprehensions as well. For example, {v for row in matrix for v in row} gives the unique values across all rows.
Exercise
Exercise
Given orders = [["pen", "ink"], [], ["pad", "pen"]], write one comprehension that produces the list of all items from non-empty orders, and a second that produces the set of unique items. What does each print?
Show answer
items = [item for order in orders if order for item in order] prints ['pen', 'ink', 'pad', 'pen']. unique = {item for order in orders for item in order} gives {'pen', 'ink', 'pad'}, with the set's order not guaranteed. The if order test is optional here, because an empty list adds no items anyway.