A table of coordinates needs every combination of two row and column values.
What You Need to Understand
A nested comprehension is a compact form of nested loops. Read its for clauses from left to right to understand their nesting order.
When to Use It
A table of coordinates needs every combination of two row and column values.
Step-by-Step Python Example
pairs = [(row, column) for row in range(2) for column in range(3)]
print(pairs)
rows = [[1, 2], [3, 4]]
print([value for row in rows for value in row])
How the Example Works
The outer clause chooses a row, then the inner clause chooses a column or value. The list-flattening result is [1, 2, 3, 4].
Example Output
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
[1, 2, 3, 4]
[20, 40, 60, 80]
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
matrix = [[2, 4], [6, 8]]
print([number * 10 for row in matrix for number in row])
Important Behavior and Edge Cases
Deeply nested comprehensions are harder to debug. Split them into loops when conditions or transformations become complex.
Try It Yourself
Flatten a three-row list of numbers with an explicit loop and then with a comprehension.
Common Beginner Mistakes
- Deeply nested comprehensions are harder to debug. Split them into loops when conditions or transformations become complex.
- Assuming every sequence operation modifies the original data or that a tuple makes nested mutable objects immutable.
Key Takeaways
- A nested comprehension is a compact form of nested loops.
- The outer clause chooses a row, then the inner clause chooses a column or value.
- Deeply nested comprehensions are harder to debug.