Learn what a deep copy is in Python, how it differs from a shallow copy, and when to use it. Includes simple explanations, beginner-friendly code examples, and use cases for nested lists and dictionaries.
A deep copy creates a completely independent copy of an object and all nested objects inside it.
Changes made to the original object do not affect the deep copy, and vice versa.
When your object contains nested structures like:
…and you want totally independent copies, use deep copy.
Use the copy
module:
import copy
deep_copy_object = copy.deepcopy(original_object)
import copy
original = [[1, 2], [3, 4]]
deep = copy.deepcopy(original)
# Modify deep copy
deep[0][0] = 100
print("Original:", original) # Output: [[1, 2], [3, 4]]
print("Deep Copy:", deep) # Output: [[100, 2], [3, 4]]
✅ Here, changing deep[0][0]
does not affect the original list.
Feature | Shallow Copy (copy.copy() ) |
Deep Copy (copy.deepcopy() ) |
---|---|---|
Copies top-level | ✅ | ✅ |
Copies nested | ❌ (references only) | ✅ (real copies) |
Independent? | ❌ | ✅ |
import copy
original = {'a': [1, 2]}
deep = copy.deepcopy(original)
deep['a'][0] = 100
print("Original:", original) # {'a': [1, 2]}
print("Deep Copy:", deep) # {'a': [100, 2]}
Tutorials, Roadmaps, Bootcamps & Visualization Projects