Show a nested Python comprehension that builds a grid and one that flattens a grid.
A nested comprehension is a comprehension whose expression or clauses contain another comprehension. The classic shape is a grid.
# A 3x3 grid built from two loops
grid = [[row * 3 + col for col in range(3)] for row in range(3)]
print(grid)
# [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
# Flatten a grid back into one list
flat = [value for row in grid for value in row]
print(flat)
# [0, 1, 2, 3, 4, 5, 6, 7, 8]
# A dictionary keyed by row index
table = {row: [col for col in range(3)] for row in range(3)}
print(table)
# {0: [0, 1, 2], 1: [0, 1, 2], 2: [0, 1, 2]}The grid comprehension has two for clauses, and the leftmost is the outermost loop — the same nesting order as nested for statements. The row clause runs three times, and for each row the column clause runs three times, producing nine values.
The flattening comprehension reads the same way: the outer clause walks the rows and the inner clause walks the values within each row, so the output is in row order.
The dictionary version shows that the nested comprehension can produce any container, not just a list — the outer braces make it a dict and the inner square brackets make the values lists.
Two things to watch. The order of the clauses determines the order of the output, so putting the column clause first would transpose the grid. And nesting more than two levels deep is legal but quickly unreadable, which is the point at which an explicit loop is the better choice.