When copying objects in Python, behavior changes for nested data structures.
π Shallow Copy
A shallow copy creates a new outer object
but inner objects remain shared references π
import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
shallow[0].append(99)
print(original)
print(shallow)
Output:
[[1, 2, 99], [3, 4]]
[[1, 2, 99], [3, 4]]
π Nested objects are shared.
π Deep Copy
A deep copy creates a completely independent copy
including all nested objects π§
import copy
original = [[1, 2], [3, 4]]
deep = copy.deepcopy(original)
deep[0].append(99)
print(original)
print(deep)
Output:
[[1, 2], [3, 4]]
[[1, 2, 99], [3, 4]]
π No shared references.
π― Quick Difference
β’ Shallow β Copies outer layer only
β’ Deep β Copies entire structure
β’ Use deep copy for nested data
