← Back to Python, page 1

python-0010 · Medium mid

Explain shallow and deep copies of nested lists, with an example of the bug a shallow copy causes.

A shallow copy creates a new outer container but keeps references to the same inner objects, so changing a nested list through the copy also changes the original. copy.deepcopy recursively copies the nested objects, giving a fully independent structure. Plain assignment copies neither; it only adds another name for the same object.

Full answer
python
import copy
grid = [[1, 2], [3, 4]]
alias = grid
shallow = copy.copy(grid)
deep = copy.deepcopy(grid)

shallow[0][0] = 99
shallow.append([5, 6])
deep[1][1] = -1
print("grid   ", grid)
print("alias  ", alias is grid)
print("shallow", shallow)
print("deep   ", deep)

bad = [[0] * 3] * 3
bad[0][0] = 1
print(bad)
good = [[0] * 3 for _ in range(3)]
good[0][0] = 1
print(good)

Output:

text
grid    [[99, 2], [3, 4]]
alias   True
shallow [[99, 2], [3, 4], [5, 6]]
deep    [[1, 2], [3, -1]]
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]

alias is the same object, so its change shows up everywhere. shallow is a new outer list (appending to it does not affect grid), but its rows are the same row objects, so shallow[0][0] = 99 also changed grid. deep has its own rows and stays independent.

The famous variant is [[0] * 3] * 3: the outer multiplication repeats a reference to one inner list, so setting one cell changes the whole column. Build such grids with a comprehension instead, as the last lines show.

Shallow copies are made by list(x), x[:], x.copy() and copy.copy(x). Deep copies cost more time and memory, and custom classes can control them with __deepcopy__.

python
import copy
grid = [[1, 2], [3, 4]]
alias = grid
shallow = copy.copy(grid)
deep = copy.deepcopy(grid)

shallow[0][0] = 99
shallow.append([5, 6])
deep[1][1] = -1
print("grid   ", grid)
print("alias  ", alias is grid)
print("shallow", shallow)
print("deep   ", deep)

bad = [[0] * 3] * 3
bad[0][0] = 1
print(bad)
good = [[0] * 3 for _ in range(3)]
good[0][0] = 1
print(good)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Assignment shares the object
  • Shallow copy: new container, same items
  • deepcopy copies recursively
  • [[0]*3]*3 repeats one inner list
  • Use comprehensions for grids

Common mistakes

  • Assuming list.copy() copies nested lists
  • Building 2D grids with list multiplication

Follow-ups

  • How does deepcopy handle cycles?
  • When is a shallow copy enough?

Tips

  • Track which objects are shared