List Multiplication Aliases 2D Rows
[[0] * cols] * rows copies row references, so writing one cell appears in every row; a comprehension allocates a fresh list per row and keeps edits local.
Code
# dangerous: the outer * copies row references, so both rows share one inner list
grid = [[0] * 3] * 2
grid[0][0] = 9
print("aliased:", grid)
# correct: a comprehension allocates an independent list per row
board = [[0] * 3 for _ in range(2)]
board[0][0] = 9
print("independent:", board)
# [0] * 3 by itself is fine: immutable elements carry no aliasing risk
row = [0] * 3
row[1] = 5
print("row:", row)Output
Captured from a sandboxed run of this snippet in the build pipeline.
aliased: [[9, 0, 0], [9, 0, 0]]
independent: [[9, 0, 0], [0, 0, 0]]
row: [0, 5, 0]What the code does
The file’s state is a handful of top-level bindings: grid, board, row.
What to watch for
- Standard-library end to end — copy it in and it runs.
Where it fits
The run emits 3 labeled sections — aliased:, independent:, row: — one per step.
Interactive Tools for This Topic
FAQ
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring. Its state lives in module-level bindings: `grid`, `board`, `row`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.