Desk Clarity

Everyday document & browser help

Python Matrix Rows Change Together: Build Each Mutable Row Separately

By ON Lab · Sources checked November 9, 2026

Check row identity before debugging the cell assignment. Repetition can place the same row object in several positions; create each row independently.

Reproduce the boundary in a disposable example

Assigning one cell changes several rows in a list-built matrix.

grid = [[0] * 3] * 2
assert grid[0] is grid[1]
grid[0][1] = 7
assert grid == [[0, 7, 0], [0, 7, 0]]
fixed = [[0] * 3 for _ in range(2)]
assert fixed[0] is not fixed[1]
fixed[0][1] = 7
assert fixed == [[0, 7, 0], [0, 0, 0]]
# Mutable cells need their own construction too.
cells = [[[] for _ in range(3)] for _ in range(2)]
cells[0][0].append("x")
assert cells[1][0] == [] and cells[0][1] == []
print("row and cell independence verified")

Read the result before changing application code

Values alone can conceal aliasing: all-zero rows look correct until the first edit. The identity assertions locate shared objects before modification. The final case checks another nesting level, where making rows independent would still be insufficient if each cell reused one list.

Choose the behavior your caller needs

Choose one sentinel edit and verify every other cell remains unchanged. For scalar cells, independent row construction is sufficient because replacing a number does not mutate that number. For dictionaries or lists stored as cells, construct each cell where its independent lifetime begins. Do not apply a shallow outer copy to an already shared grid and expect all levels to become independent.

Scope and limits

The example concerns nested built-in lists. Array libraries have different constructors, views and copy contracts; check those APIs separately.

Related: compare the adjacent data or execution boundary.

The embedded example was executed in an isolated local Python process on November 9, 2026. It is a reproducible boundary check, not a test of your full application.

Sources