Junior — Middle
What is the difference between deep copying objects in Python and shallow copying, and when should it be used?
sobes.tech AI
Answer from AI
In Python, shallow copying creates a new object, but nested objects within it are not copied; they are simply referenced. Deep copying creates a new object and recursively copies all nested objects, creating a completely independent structure.
When to use:
- Shallow copy is suitable if nested objects will not be modified or if changes to nested objects should be reflected in both copies.
- Deep copy is necessary when a fully independent copy of the object with all nested elements is required, so that changes in the copy do not affect the original.
Example:
import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
shallow[0][0] = 100
print(original) # [[100, 2], [3, 4]] - original has changed
deep[1][1] = 200
print(original) # [[100, 2], [3, 4]] - original remains unchanged
Thus, the choice between shallow and deep copying depends on the requirements for copy independence.