Understanding the difference between shallow copy and deep copy is key when working with mutable objects in Python like lists, dictionaries, or custom classes.
๐ฆ What is a Shallow Copy?
A shallow copy creates a new object, but inserts references to the original objects inside it.
โ Example:
import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
shallow[0][0] = 99
print(original) # [[99, 2], [3, 4]]
๐ฏ Original is affected because inner objects are shared.
๐ What is a Deep Copy?
A deep copy creates a new object and recursively copies all nested objects.
โ Example:
import copy
original = [[1, 2], [3, 4]]
deep = copy.deepcopy(original)
deep[0][0] = 99
print(original) # [[1, 2], [3, 4]]
โ Original is NOT affected because everything is duplicated.
๐ Comparison Table
Feature | Shallow Copy | Deep Copy |
---|---|---|
New outer object? | โ Yes | โ Yes |
New inner objects? | โ No (shared) | โ Yes (copied) |
Uses copy.copy()
|
โ | โ |
Uses copy.deepcopy()
|
โ | โ |
๐งช When to Use Which?
-
Use shallow copy if:
- Your object has only immutable or flat structure
- You want faster performance
-
Use deep copy if:
- Your object has nested mutable objects
- You want full isolation
๐ Pro Tip
Custom classes may need a custom __deepcopy__()
method if they hold external references or open files.
Top comments (0)