Middle
What are the mechanisms for copying objects in Python?
sobes.tech AI
Answer from AI
In Python, there are two main mechanisms for copying objects:
-
Shallow copy — creates a new object, but nested objects inside it remain references to the original. The
copy.copy()function is used. -
Deep copy — creates a new object and recursively copies all nested objects, completely separating the copy from the original. The
copy.deepcopy()function is used.
Example:
import copy
original = [1, [2, 3], 4]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
original[1][0] = 'changed'
print(shallow) # [1, ['changed', 3], 4] — nested list has changed
print(deep) # [1, [2, 3], 4] — nested list remains the same
For simple objects, slices or constructors (e.g., list(original)) can also be used, but they usually perform shallow copies.