Middle+
Tell us about the copy module in Python. What is the difference between copy and deepcopy?
sobes.tech AI
Answer from AI
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.
- Deep copy recursively copies all nested objects, creating a fully 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 remains unchanged