What is the difference between a shallow copy and a deep copy in Python?
Short answer
A shallow copy duplicates the outer container but shares the nested objects, so changes to a nested item show in both. A deep copy duplicates everything recursively, giving full independence.
The short version
A shallow copy makes a new outer container but reuses the same inner objects, so editing a nested item changes both copies. A deep copy recreates every level, so the two are fully independent. The distinction only matters when your data contains nested mutable objects like lists inside lists.
Seeing a shallow copy leak
import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
shallow[0].append(99)
print(original) # [[1, 2, 99], [3, 4]]
The outer list was copied, but shallow[0] and original[0] are the same inner list, so appending to one shows in the other. This is the surprise that catches people.
A deep copy stays separate
original = [[1, 2]]
deep = copy.deepcopy(original)
deep[0].append(99)
print(original) # [[1, 2]]
deepcopy rebuilt the inner list too, so the change is contained.
When shallow is fine
If the container holds only immutable items like numbers, strings or tuples, a shallow copy is effectively independent, because you cannot mutate those items in place. So a flat list of numbers can be safely copied with list(x) or x[:], and you never need deepcopy.
nums = [1, 2, 3]
copy_of_nums = nums[:] # independent, no nesting to share
The assignment that is not a copy at all
The most common bug is thinking = copies. It does not; it makes a second name for the same object.
a = [1, 2]
b = a # not a copy
b.append(3)
print(a) # [1, 2, 3]
If you want any independence, you must copy explicitly.
Cost and choice
deepcopy is slower and can be surprisingly expensive on large nested structures, and it can even fail on objects that cannot be pickled. So do not reach for it by default. Use a shallow copy when the contents are immutable or you do not intend to mutate nested parts, and deepcopy only when you truly need every level to be independent.