Junior — Middle
What is the difference between shallow and deep copy functions in Python?
sobes.tech AI
Answer from AI
In Python, copying functions are divided into shallow and deep copying.
Shallow copy creates a new object, but nested objects within it are not copied, only references to them are copied. That is, if the object contains mutable elements (e.g., lists, dictionaries), changes to them will reflect in the copy.
Deep copy creates a new object and recursively copies all nested objects, so the copy is completely independent of the original.
Example:
import copy
original = [1, [2, 3], 4]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
shallow[1].append(5)
print(original) # [1, [2, 3, 5], 4] - nested list changed
print(shallow) # [1, [2, 3, 5], 4]
print(deep) # [1, [2, 3], 4] - deep copy did not change
Thus, shallow copy is faster but can lead to unexpected changes in nested objects, while deep copy is safer but more resource-intensive.