Middle+
How to implement copy and deepcopy functions in Python?
sobes.tech AI
Answer from AI
The implementation of copy and deepcopy is based on the copy module.
For copy:
Creates a shallow copy of an object. For composite objects (lists, dictionaries, etc.), it creates a new container, but the elements inside are references to the original objects.
import copy
# Original list
original_list = [[1, 2], [3, 4]]
# Shallow copy
copied_list = copy.copy(original_list)
# Modifying an element in the nested list of the original
original_list[0][0] = 99
# copied_list[0][0] will also change, as both lists refer to the same nested list
For deepcopy:
Creates a deep copy of an object. It creates new containers and recursively copies all elements inside composite objects.
import copy
# Original dictionary
original_dict = {'a': [1, 2], 'b': {'c': 3}}
# Deep copy
deep_copied_dict = copy.deepcopy(original_dict)
# Modifying an element in the nested list of the original
original_dict['a'][0] = 99
# deep_copied_dict['a'][0] will remain unchanged
Key differences:
| Characteristic | copy.copy() |
copy.deepcopy() |
|---|---|---|
| Nested objects | Performs a shallow copy, references original objects. | Performs a recursive copy. |
| Efficiency | Faster for large structures. | Slower for large structures. |
| Memory consumption | Less. | More. |
| Modification of original | May affect the copied object. | Does not affect the copied object. |