PYTHON / CHAPTER 09
Comprehensions and nested aliasing
IntermediateExpress transformations without creating shared mutable rows.
By the end of this chapter
- Trace filter and mapping order
- Construct independent nested lists
- Compare a shallow copy with independent rows
The idea
A list comprehension evaluates its source, filters selected elements, and computes an output expression for each retained item. Read the for clauses from left to right, just as nested loops. Keep the expression short enough to inspect; a named helper or ordinary loop is clearer when the transformation includes several decisions or effects.
Construction also determines sharing. Multiplying a list containing one mutable row repeats references to that row. Changing one displayed row can then change every row. A comprehension that creates a fresh inner list for each iteration produces independent rows. A shallow outer copy does not repair already shared inner objects. Test identity or mutate one row intentionally when verifying a grid constructor.
grid = [[0] * 2 for _ in range(3)]
grid[0][1] = 7
print(grid)
print([n * n for n in range(5) if n % 2])[[0, 7], [0, 0], [0, 0]] [1, 9]
Each comprehension iteration constructs its own row; only odd n values enter the second result.
Try it yourself
Create a rectangular grid with independent rows, then flatten only its positive values.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
Open Python coding challengesCHECK YOUR UNDERSTANDING