Junior — Middle
How to implement copying objects in Python to create a full or shallow copy?
sobes.tech AI
Answer from AI
In Python, the copy module with functions copy() and deepcopy() are used for copying objects.
copy.copy(obj)creates a shallow copy of the object — only the object itself is copied, and nested objects remain shared.copy.deepcopy(obj)creates a full (deep) copy, recursively copying all nested objects.
Example:
import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
original[0][0] = 99
print(shallow) # [[99, 2], [3, 4]] — nested objects are shared
print(deep) # [[1, 2], [3, 4]] — nested objects are copied