- Published on
9. Shallow copy vs of Deep copy
- Authors
9. When should you use shallow copy instead of deep copy, and vice versa?
The decision between using a shallow copy and a deep copy depends on the structure of your data and how much independence you want between the copy and the original.
π Shallow Copy
A shallow copy creates a new outer object, but does not clone nested (inner) objects β it just copies references to them.
Use When:
- Your data structure is flat (no nested objects).
- You want a new container, but are okay sharing the same inner objects.
- You care about performance and donβt need full independence.
Example:
import copy
original = [1, 2, [3, 4]]
shallow = copy.copy(original)
shallow[2][0] = 99
print(original) # [1, 2, [99, 4]] β original was affected!
𧬠Deep Copy
A deep copy creates a completely independent clone, recursively copying all nested objects.
Use When:
- Your data contains nested structures (lists inside lists, dicts inside dicts, etc.).
- You need full independence between the original and the copy.
- You want to prevent accidental changes to shared nested objects.
Example:
import copy
original = [1, 2, [3, 4]]
deep = copy.deepcopy(original)
deep[2][0] = 99
print(original) # [1, 2, [3, 4]] β original remains unchanged
π§ Summary:
Feature | Shallow Copy | Deep Copy |
---|---|---|
Copies outer object? | β Yes | β Yes |
Copies inner objects? | β No (shared references) | β Yes (fully independent) |
Performance | Faster | Slower (recursive) |
Use case | Flat or reference-safe data | Nested or modification-sensitive data |