Why does `grid = [[0] * 3] * 3` create a broken 3x3 grid, and what is the correct way to build a nested list?
Answer
`[[0] * 3] * 3` first creates one inner list `[0, 0, 0]`, then the outer `* 3` repeats a reference to that exact same inner list object three times, so all three rows alias each other and mutating one row mutates all of them. The fix is to build each row independently, typically with a comprehension: `grid = [[0] * 3 for _ in range(3)]`, which evaluates `[0] * 3` fresh on every iteration and produces three distinct list objects.
Strong answer includes
- * on a list repeats references, not copies
- all rows alias the same inner list
- fix with a comprehension that builds each row separately
Practical example
After
grid = [[0] * 3] * 3, running
grid[0][0] = 1changes `grid` to
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]because every row is the same object.