The assignment of objects in Python is actually a reference to the object. When an object is created and assigned to another variable, Python does not copy the object, only the reference to the object.
#Shallow copy: The outermost object itself is copied, and the internal elements are just copied with a reference. That is, the object is copied once, but other objects referenced in the object are not copied
Deep copy: Both peripheral and internal elements copy the object itself, not the references. That is, the object is copied once, and other objects referenced in the object are also copied.
The role of deep and shallow copy
1. Reduce memory usage
2. In the future, when cleaning, modifying or storing data, Make a copy of the original data to prevent the original data from being found after the data is modified.
Related recommendations: "Python Video Tutorial"
Shallow copy (copy): Copies the parent object and does not copy the internal child objects of the object.
Deep copy (deepcopy): The deepcopy method of the copy module completely copies the parent object and its child objects.
>>>a = {1: [1,2,3]} >>> b = a.copy() >>> a, b({1: [1, 2, 3]}, {1: [1, 2, 3]}) >>> a[1].append(4) >>> a, b({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})
Deep copy requires the introduction of the copy module:
>>>import copy >>> c = copy.deepcopy(a) >>> a, c({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]}) >>> a[1].append(5) >>> a, c({1: [1, 2, 3, 4, 5]}, {1: [1, 2, 3, 4]})
1. b = a.copy(): Shallow copy, a and b are an independent object, but their sub-objects still point to Unified object (is a reference).
2. b = copy.deepcopy(a): Deep copy, a and b completely copy the parent object and its child objects, and they are completely independent.
The above is the detailed content of The difference between deep and shallow copy in python. For more information, please follow other related articles on the PHP Chinese website!