Python shallow copy vs deep copy

Backend Live Coding November 13, 2026 python

A shallow copy (list(x), x.copy(), copy.copy) creates a new outer object but shares the inner ones.

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# ======================================================================
# Q: What is the difference between a shallow copy and a deep copy?
#
# A shallow copy (list(x), x.copy(), copy.copy) creates a new outer object but
# shares the inner ones. A deep copy (copy.deepcopy) recursively copies
# everything.
# ======================================================================

a = [[1, 2], [3]]
b = a.copy()          # shallow
b[0].append(99)
print(a)              # [[1, 2, 99], [3]]  <- a changed too
c = copy.deepcopy(a)  # independent copy