Middle+
Räägi mulle Pythonis kasutatavast copy modulist. Mis vahe on copy ja deepcopy vahel?
sobes.tech AI
Vastus AI-lt
The copy module in Python provides functions for creating copies of objects. Main functions:
copy.copy(obj)— shallow copy.copy.deepcopy(obj)— deep copy.
Difference between copy and deepcopy:
- Shallow copy creates a new object, but nested objects inside it are not copied, only referenced to the same objects as in the original.
- Deep copy recursively copies all nested objects, creating a completely independent copy.
Example:
import copy
original = [1, [2, 3]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
original[1][0] = 'changed'
print(shallow) # [1, ['changed', 3]] — nested list changed
print(deep) # [1, [2, 3]] — deep copy unchanged