Sub topic 7
Multiple for clauses and flattening nested data
This chapter assumes you can already write a single-clause list comprehension with an optional trailing if. You should also be comfortable with nested lists, tuples, and for loops. Here you will learn to put several for clauses in one comprehension, read them in the right order, and use them to flatten nested data and build combinations.
One comprehension, several loops
A comprehension can contain more than one for clause. Each extra clause behaves like another loop nested inside the previous one. The rule is simple: read the for clauses from left to right, and treat each one as indented one level deeper than the one before.
Here is a nested loop that flattens a matrix, followed by its comprehension form.
matrix = [[1, 2, 3], [4, 5, 6]]
flat = []
for row in matrix:
for value in row:
flat.append(value)
print(flat) # [1, 2, 3, 4, 5, 6]
flat = [value for row in matrix for value in row]
print(flat) # [1, 2, 3, 4, 5, 6]The output expression value moves to the front. The two for clauses keep the same order they had in the loop version: for row in matrix first, then for value in row.
The following diagram shows how the clauses unfold.
The mapping to nested loops
Every comprehension with several clauses can be rewritten as nested statements. The output expression becomes the append call at the innermost level.
| Comprehension part | Equivalent in a loop |
|---|---|
| First `for` clause | Outermost `for` statement |
| Next `for` clause | `for` statement indented one level deeper |
| `if` clause | `if` statement at the level where it appears |
| Output expression at the front | Argument to `append` in the innermost body |
The output expression is written first but runs last. Only the position in the text differs from the loop. The execution order is the same.
Combining two iterables
Multiple for clauses are not only for flattening. They also produce every combination of two or more sequences, which is a Cartesian product.
pairs = [(x, y) for x in range(3) for y in range(3) if x < y]
print(pairs) # [(0, 1), (0, 2), (1, 2)]
shirts = [(color, size) for color in ("red", "blue") for size in ("S", "M")]
print(shirts)
# [('red', 'S'), ('red', 'M'), ('blue', 'S'), ('blue', 'M')]In shirts, the outer clause moves slowest. Each color is paired with every size before the next color is taken. If you want sizes to vary slowest, swap the two for clauses.
The first example also shows a trailing if. It sits after both for clauses, so it is tested once for every (x, y) combination. The condition x < y throws away the diagonal and mirrored pairs, leaving each unordered pair once.
Where the order matters
The order of for clauses decides which names exist when each clause runs. The inner clause may use the variable from the outer clause, but not the other way round.
matrix = [[1, 2, 3], [4, 5, 6]]
try:
wrong = [value for value in row for row in matrix]
except NameError as error:
print(error) # name 'row' is not definedThe loop variable row is created by the second clause. The first clause tries to use it before it exists, so Python raises NameError. This is the most common mistake with nested comprehensions. A reliable habit is to write the loops as ordinary nested statements first, then copy the for lines across in the same order and move the output expression to the front.
A related trap is that the names are easy to misread when the loop variable names look alike. Use names that say what they hold, such as row and value, or order and item. Avoid i, j, and k when real names are available.
The inner iterable can depend on the outer variable
In a Cartesian product the two iterables are independent. When flattening, the inner iterable comes from the outer variable. Both are the same syntax. This lets you walk through data of uneven shape.
jagged = [[1, 2, 3], [4], [], [5, 6]]
flat = [v for row in jagged for v in row]
print(flat) # [1, 2, 3, 4, 5, 6]Empty rows contribute nothing. The inner loop simply runs zero times, so you do not need a special case.
Strings are iterable too, so the same pattern splits a list of words into characters.
words = ["ab", "cd"]
chars = [ch for word in words for ch in word]
print(chars) # ['a', 'b', 'c', 'd']This works well for strings because every element of a string is a one-character string. The next section shows what goes wrong when you expect it to work on mixed data.
Filtering at more than one level
An if clause can appear after any for clause, not only at the end. Placing it early skips work. Rows that fail the test are never entered, so their inner loop does not run.
jagged = [[1, 2, 3], [4], [5, 6]]
evens_in_long_rows = [
v
for row in jagged
if len(row) > 1
for v in row
if v % 2 == 0
]
print(evens_in_long_rows) # [2, 6]Read it as a loop nest:
jagged = [[1, 2, 3], [4], [5, 6]]
result = []
for row in jagged:
if len(row) > 1:
for v in row:
if v % 2 == 0:
result.append(v)
print(result) # [2, 6]The row [4] is rejected by the first test, so its 4 is never examined. If you moved len(row) > 1 to the end, the comprehension would not be valid in the same way. The test would then run once per value, and it would only be able to see row and v at the innermost level. Put each filter as early as the names it needs allow.
Breaking the comprehension across several lines, one clause per line, makes the structure visible. The formatter style shown above is the usual convention for anything longer than one short line.
Three or more levels
The pattern continues for deeper data. Each added level adds one for clause.
cube = [[[1, 2], [3]], [[4], [5, 6]]]
values = [v for plane in cube for row in plane for v in row]
print(values) # [1, 2, 3, 4, 5, 6]This flattens fully because the nesting depth is known and constant. It does not scale to data of unknown depth. If the structure can nest arbitrarily, a comprehension is the wrong tool, because you would need a different number of for clauses for each input. A recursive generator handles this case.
def flatten(items):
for item in items:
if isinstance(item, list):
yield from flatten(item)
else:
yield item
print(list(flatten([1, [2, [3, 4]], 5]))) # [1, 2, 3, 4, 5]Be careful when checking types in a function like this. Strings are iterable, so a check such as isinstance(item, Iterable) would recurse forever on a one-character string. Testing for list (or (list, tuple)) avoids that.
Multiple clauses versus nested comprehensions
Multiple for clauses produce one flat result. A comprehension nested inside another one produces a list of lists. The two look similar but answer different questions.
matrix = [[1, 2, 3], [4, 5, 6]]
# One flat list: two for clauses in one comprehension.
flat = [value * 2 for row in matrix for value in row]
print(flat) # [2, 4, 6, 8, 10, 12]
# Same shape as the input: an inner comprehension builds each row.
doubled = [[value * 2 for value in row] for row in matrix]
print(doubled) # [[2, 4, 6], [8, 10, 12]]Ask what shape you want. If the result keeps the rows, put a comprehension inside the output expression. If the result is a single sequence, use several for clauses. A transposition is a good example of the nested form, where the inner comprehension builds each new row.
matrix = [[1, 2, 3], [4, 5, 6]]
transposed = [[row[i] for row in matrix] for i in range(3)]
print(transposed) # [[1, 4], [2, 5], [3, 6]]The standard library also offers zip(*matrix) for this job, and itertools.chain.from_iterable for flattening one level. Both are fine alternatives.
from itertools import chain
matrix = [[1, 2, 3], [4, 5, 6]]
print(list(chain.from_iterable(matrix))) # [1, 2, 3, 4, 5, 6]chain.from_iterable is lazy and has no clause order to get wrong. Use it when you only need to flatten and not transform or filter.
Dict and set comprehensions with several clauses
Everything in this chapter applies to dict and set comprehensions as well. The clauses come after the key and value, or after the single set element.
table = {(x, y): x * y for x in range(1, 3) for y in range(1, 3)}
print(table) # {(1, 1): 1, (1, 2): 2, (2, 1): 2, (2, 2): 4}
sums = {a + b for a in (1, 2) for b in (1, 2)}
print(sums) # {2, 3, 4}The same duplicate rules still hold. In the set, the sum 3 is produced twice but stored once. In a dict comprehension, if two combinations produce the same key, the later one overwrites the earlier one. In table this does not happen because each (x, y) tuple is unique.
Size of the result
The number of iterations is the product of the sizes of the loops, not the sum. Two clauses over 1,000 items each run the body 1,000,000 times. A list comprehension builds all those results in memory at once.
count = sum(1 for x in range(1000) for y in range(1000))
print(count) # 1000000Here the parentheses of sum(...) hold a generator expression, so no list of a million items is built. Use a generator expression whenever you only need to consume the combinations once, for example to count them, sum them, or find the first match with any or next.
When to stop and write a loop
Two for clauses are usually readable. A third clause, or two clauses combined with several filters, often is not. A reader has to hold the whole loop nest in their head, and a mistake in clause order produces either a NameError or silently wrong results.
Prefer a loop or a helper function when:
- the inner iterable needs several lines of logic to compute,
- you need to stop early with
break, which comprehensions cannot do, - you need to handle errors for individual items, or
- the data has an unknown depth.
Summary of the rules
- List the
forclauses in the same order as the nested loops they replace. - The output expression goes first but runs at the innermost level.
- A variable can be used only by clauses to its right, so the outer variable must come first.
- Put
ifclauses as early as possible to skip unneeded work. - Several
forclauses give a flat result. A comprehension inside a comprehension keeps the nesting. - The loop count is the product of the loop sizes, so consider a generator expression for large inputs.
Exercise
Given orders = [["pen", "ink"], [], ["pad", "pen", "tape"]], write one comprehension that produces a flat list of every item whose name has three letters, in the order they appear. Then say what happens if you write the two for clauses in the opposite order.
Show answer
Use [item for order in orders for item in order if len(item) == 3]. The result is ['pen', 'ink', 'pad', 'pen']. The empty order contributes nothing. If you swap the clauses to for item in order for order in orders, Python raises NameError: name 'order' is not defined, because the first clause uses order before the second clause creates it.
Exercise
What does [(a, b) for a in "xy" for b in range(2)] return, and how many times does the output expression run if you replace "xy" with a 4-character string and range(2) with range(5)?
Show answer
It returns [('x', 0), ('x', 1), ('y', 0), ('y', 1)]. The outer variable a changes slowest. With a 4-character string and range(5) the expression runs 4 * 5 = 20 times, because the iteration count is the product of the loop sizes.
Exercise
You have grid = [[1, 2], [3, 4]]. Write one comprehension that returns [[10, 20], [30, 40]] and another that returns [10, 20, 30, 40]. What is the structural difference between them?
Show answer
The first is [[v * 10 for v in row] for row in grid], which has a comprehension inside the output expression and keeps the rows. The second is [v * 10 for row in grid for v in row], which uses two for clauses in one comprehension and produces a single flat list.