Advertisement
Intermediate Python, Data Types & Structures

What's the difference between shallow copy and deep copy for a nested data structure, and which functions perform each?

Short answer

A shallow copy (via list.copy(), dict.copy(), or copy.copy()) creates a NEW outer container but still references the SAME nested/inner objects — mutating a nested list inside a shallow copy affects the original too.

Save Python mock interview
Advertisement
AModel answer
A shallow copy (via list.copy(), dict.copy(), or copy.copy()) creates a NEW outer container but still references the SAME nested/inner objects — mutating a nested list inside a shallow copy affects the original too. A deep copy (via copy.deepcopy()) recursively copies EVERY nested object, producing a fully independent structure.
import copy

original = [[1, 2], [3, 4]]
shallow = original.copy()
shallow[0].append(99)
print(original)  # [[1, 2, 99], [3, 4]] -- original affected too!

deep = copy.deepcopy(original)
deep[0].append(100)
print(original)  # unaffected by the deep copy's mutation
Real-world example
Safely duplicating a nested configuration dictionary before modifying it, without accidentally corrupting the original.
Likely follow-ups
  • Why is a plain assignment (new_list = old_list) NOT even a shallow copy, but something different entirely?
Related topics