Nested comprehensions in Python
Comprehensions over two dimensions: grids and matrices.
grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [cell for row in grid for cell in row]
doubled = [[cell * 2 for cell in row] for row in grid]
diagonal = [grid[i][i] for i in range(len(grid))]
coords = [(r, c) for r in range(3) for c in range(3) if r != c]
table = {r: [c * r for c in range(4)] for r in range(3)}
How it works
- Two
forclauses flatten a grid of rows into cells. - A comprehension inside a comprehension rebuilds rows.
- The pattern extends to dict comprehensions of lists.
Keywords and builtins used here
foriflenrange
The run, in numbers
- Lines
- 9
- Characters to type
- 315
- Tokens
- 130
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 78 seconds.
Step 3 of 4 in Comprehensions, step 3 of 53 in Pythonic Python.