Skip to main content

Python Nested Lists

List Satellite

Nested Lists

Represent grids, matrices, and hierarchies by embedding lists. Learn how to access, copy, and iterate them safely.

Creation

grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]

Avoid [[0] * 3] * 4 because it reuses references. Prefer comprehensions:

grid = [[0 for _ in range(cols)] for _ in range(rows)]

Access

grid[row][col]

Loop over rows and columns:

for r, row in enumerate(grid):
for c, value in enumerate(row):
...

Next up in your learning path