The difference between copy()
and deepcopy()
in Python lies in how they handle nested objects (mutable objects inside other objects like lists or dictionaries).
copy()
(Shallow Copy)import copy
original = [[1, 2, 3], [4, 5, 6]]
shallow_copy = copy.copy(original)
shallow_copy[0][0] = 99 # Modifying a nested list
print(original) # Output: [[99, 2, 3], [4, 5, 6]] (Changed!)
print(shallow_copy) # Output: [[99, 2, 3], [4, 5, 6]]
* Best for non-nested objects or when modifying nested elements is acceptable.
deepcopy()
(Deep Copy)import copy
original = [[1, 2, 3], [4, 5, 6]]
deep_copy = copy.deepcopy(original)
deep_copy[0][0] = 99 # Modifying a nested list
print(original) # Output: [[1, 2, 3], [4, 5, 6]] (Unchanged!)
print(deep_copy) # Output: [[99, 2, 3], [4, 5, 6]]
* Best for deeply nested structures where modifications should be independent.
Feature | copy() (Shallow Copy) |
deepcopy() (Deep Copy) |
---|---|---|
Creates a new object? | Yes | Yes |
Copies nested objects? | No (references same objects) | Yes (new copies of all objects) |
Modifying nested objects affects original? | Yes | No |
Performance | Faster | Slower (more memory usage) |
Best for | Flat structures, minimal nesting | Deeply nested data |