Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Data types & structuresMiddleCommonTroubleshooting

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

Python example
grid = [[0] * 3] * 3

, running

Python example
grid[0][0] = 1

changes `grid` to

Python example
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

because every row is the same object.

#lists#aliasing#gotchas

Sources

The Python Standard LibraryPython Software Foundation · Authoritative behavior for built-in types and standard library modulesThe Python TutorialPython Software Foundation · Baseline syntax, control flow, functions and module basics