Shallow vs Deep Copy
Overview
When you duplicate collections in Python, you must understand how deep the copy goes. Standard assignment (a = b) copies nothing; it just adds a new reference pointer. A Shallow Copy (.copy() or [:]) creates a new outer collection, but populates it with references to the original inner objects. A Deep Copy (copy.deepcopy()) is fully recursive: it physically clones the outer collection AND every single nested object inside it, creating a totally independent duplicate.
Syntax
import copy
# A list containing a nested mutable object (another list)
original = [[1, 2], [3, 4]]
# 1. Assignment (Exact same object in memory)
ref = original
# 2. Shallow Copy (Copies outer list, shares inner lists)
shallow = original.copy()
# 3. Deep Copy (Fully recursive clone)
deep = copy.deepcopy(original)
# Modify the nested object
original[0][0] = 99
# Let's inspect the damage
print(shallow[0][0]) # 99 (It was mutated! They share the inner list)
print(deep[0][0]) # 1 (Totally safe, independent clone)Common Pitfalls
- Assuming slicing
my_list[:]creates a completely independent duplicate. If the list contains complex mutable objects (like dicts or other lists), those inner objects are still intrinsically linked. - Using
deepcopyon massive, deeply nested data structures indiscriminately. It is incredibly slow and consumes massive amounts of memory. Use it sparingly.
Interview Questions
When your collection contains ONLY immutable objects (like integers, strings, or tuples). Since the inner objects cannot be mutated anyway, sharing references to them is perfectly safe and memory efficient.
Real-World Example
Cloning a deeply nested default JSON configuration before applying user-specific tweaks.
import copy
default_settings = {
"theme": "dark",
"layout": {"sidebar_visible": True, "font_size": 12}
}
# Must use deepcopy so we don't accidentally mutate the global layout dict
user_settings = copy.deepcopy(default_settings)
user_settings["layout"]["sidebar_visible"] = FalseCheck Your Knowledge
Test your understanding of Shallow vs Deep Copy with these quick questions.