Read Nested Comprehensions in Loop Order
Core idea
A comprehension can contain multiple for clauses. Read them as nested loops in their written order: the first for is the outer loop, the next is the inner loop. The result expression runs for each combination that reaches the innermost step. A later iterable can depend on an earlier item.
print([(row, col) for row in [1, 2] for col in [3, 4]])The inner column loop completes for each row.
Flatten rows
rows = [[2, 5], [], [7]]flat = [n for row in rows for n in row]print(flat)The empty row contributes nothing. This flattens one level only.
Keep the rows instead
rows = [[2, 5], [7]]print([[n * 2 for n in row] for row in rows])The result expression is itself a comprehension, so each output item is a list.
Common mistake
Do not reverse the for clauses when the inner iterable depends on the outer item. Use explicit nested loops if the expression is hard to follow.
Practice
Flatten [[1], [], [2, 3]] and then write the two equivalent for loops with append.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Nested comprehension order
Check your understanding of nested comprehensions.
What is printed?
print([(a, b) for a in [1, 2] for b in [5, 6]])What is printed?
print([n for row in [[], [4, 5]] for n in row])What is printed?
print([[n * 2 for n in row] for row in [[1], [3, 4]]])Which for clause corresponds to the outer loop?