Python, an assignment statement does not copy the object, but create a binding relationship between the objectives and targets. For their collection object contains a variable or variable items, developers may need to be generated for changing a copy operation, thereby avoiding changing the original object. copy module provides a common replication shallow copy()
and deep copy deepcopy()
operations.
-
copy()
Copy only the object itself, not on the child objects which may be reproduced if modify atomic object, then the object after the shallow copy will be with the changes. -
deepcopy()
Is replicated in the true sense, that is, to re-open up a space, often say that the object is actually copied after deepcopy, deep copy without affecting the original object, no matter what changes the original object occurs, a deep copy of the object will not change .
>>> import copy
>>> list1 = [1, 2, [3, 4], 5]
>>> list2 = copy.copy(list1)
>>> list3 = copy.deepcopy(list1)
>>> list2 == list3
True
>>> list2 is list3
False
More than two lists list2 and list3 respectively after a shallow copy and a deep copy, although the value is the same, but the same is not a list of essence
>>> import copy
>>> list1 = [1, 2, [3, 4], 5]
>>> list2 = copy.copy(list1)
>>> list3 = copy.deepcopy(list1)
>>> list1[2][0] = 3333
>>> list1
[1, 2, [3333, 4], 5]
>>> list2
[1, 2, [3333, 4], 5]
>>> list3
[1, 2, [3, 4], 5]
The original list of sub-objects [3, 4]
into [333, 4]
, you can see the shallow copy list2 values will change, and after a deep copy list3 value does not change.
simply put:
- Shallow copy
copy()
: Copies parent, child objects still use reference; - Deep Copy
deepcopy()
: Copy all child objects objects and objects.