โ† Back

Home โ€บ Output practice โ€บ two names, one list

Predict the output: two names, one list

๐Ÿ”ฎ Predict the outputTopic: listsDifficulty: mediumNo login needed

The snippet

[row, row] looks like a grid of two rows. It is a list holding the same row twice โ€” and list.copy() is shallow, so it does not fix that either.

row = [0, 0]
grid = [row, row]
grid[0][1] = 9
print(grid)
print(row)

Your prediction

Type exactly what this program prints โ€” one line per print() call:

The output

[[0, 9], [0, 9]]
[0, 9]

Verified against CPython 3.11 in this repo's build

Line-by-line explanation

  1. row = [0, 0]
    One list object is created; row is a name pointing at it.
  2. grid = [row, row]
    No new lists are built. grid holds two references to the *same* object โ€” this is the whole bug in one line.
  3. grid[0][1] = 9
    grid[0] is row, so this mutates that single shared list in place.
  4. print(grid)
    Both slots read the same mutated object โ†’ [[0, 9], [0, 9]].
  5. print(row)
    row was never copied either โ†’ [0, 9]. The change is visible from every name that points at the object.

The rule you can reuse

Assignment and list literals copy references, never objects. For nested data use copy.deepcopy, or rebuild each row so the rows are distinct objects.

Why most predictions break here

Expecting [[0, 9], [0, 0]]. The rows do not become separate objects just because you drew them as a grid โ€” ask "how many list objects exist?" (one row) before writing the answer.

Quick fire

Same rule, two more shapes. Predict first, then open.

Predict this too
a = [[1, 2], [3, 4]]
b = a.copy()
b[0].append(5)
print(a)
print(b is a, b[0] is a[0])

Output
[[1, 2, 5], [3, 4]]
False True

copy() gives a new outer list but the same inner ones, so a sees the append: [[1, 2, 5], [3, 4]] then False True.

Predict this too
rows = [[0] * 2] * 3
rows[0][0] = 1
print(rows)

Output
[[1, 0], [1, 0], [1, 0]]

* 3 repeats one object three times, so every row changes: [[1, 0], [1, 0], [1, 0]]. Build rows in a comprehension to get three real rows.

Share your result

Challenge a friend โ€” the link contains the question, never the answer:

Copied โœ“

Keep practising this rule

More output questions โ†’ All interactive problems

Questions this page answers

Why does Python not copy on assignment?

Because copying large objects implicitly would be slow and surprising. Python passes references; is tells you whether two names share an object and == whether their contents match.

So is `[0] * 3` always wrong?

For immutable items like 0 or "" it is perfectly safe. It only bites when the repeated element is itself mutable โ€” a list, dict or object.