List multiplication and shallow copy aliasing
Predict both grids after mutating one nested cell.
Code Snippet
grid = [[0] * 2] * 3
grid[0][1] = 7
copy_grid = grid.copy()
copy_grid[1][0] = 9
print(grid)
print(grid[0] is grid[2])Expected Output & Explanation
[[9, 7], [9, 7], [9, 7]]
True [[0] * 2] * 3 repeats references to the exact same inner list three times. grid.copy() makes a shallow copy of the outer list, still pointing to that same inner list. Build independent rows with [[0] * 2 for _ in range(3)].
Follow-up Interview Question · When does copy.deepcopy still share references or fail?
Module Context & References
Python · Predict the output & bug traps Widely asked Python gotchas: defaults, closures, scoping, copies and async
Personal Notes · Markdown