Show a nested Python comprehension that builds a grid and one that flattens a grid.
A nested comprehension is a comprehension whose expression, or whose 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 = []
for row in grid:
for value in row:
flat.append(value)
print(flat)
# [0, 1, 2, 3, 4, 5, 6, 7, 8]
# A dictionary keyed by row index.
table = {}
for row in range(3):
table[row] = [col for col 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 one is the outermost loop, which is the same nesting order that you get from nested for statements. The row clause runs three times, and for each row the column clause runs three times, which produces nine values in the end.
The flattening code reads in the same way. The outer loop walks the rows and the inner loop walks the values inside each row, so the output comes out in row order.
The dictionary version shows that a nested comprehension can produce any container and not only a list. The outer curly braces make it a dictionary, and the inner square brackets make the values lists.
There are two things to watch. The order of the clauses decides the order of the output, so putting the column clause first would turn the grid on its side. And nesting more than two levels deep is perfectly legal, but it becomes very hard to read, which is the point at which an explicit loop is the better choice.