Python copy, the difference between deep copy and shallow copy

Written before :
.copy() copy and [:] copy in python are both shallow copies

In python, object assignment is actually a reference to an object. When creating an object and then assigning it to another variable, python does not copy the object, but only copies the reference to the object.
Generally, there are three methods:

eg:
alist=[1,2,3,["a","b"]]

(1) Direct assignment, pass the reference of the object, the original list changes, the assigned b will also make the same change

>>> b=alist
>>> print b
[1, 2, 3, ['a', 'b']]
>>> alist.append(5)
>>> print alist;print b
[1, 2, 3, ['a', 'b'], 5]
[1, 2, 3, ['a', 'b'], 5]

(2) copy shallow copy, no sub-object is copied, so the original data changes, the sub-object will change

>>> import copy
>>> c=copy.copy(alist)
>>> print alist;print c
[1, 2, 3, ['a', 'b']]
[1, 2, 3, ['a', 'b']]
>>> alist.append(5)
>>> print alist;print c
[1, 2, 3, ['a', 'b'], 5]
[1, 2, 3, ['a', 'b']]
>>> alist[3]
['a', 'b']
>>> alist[3].append('cccc')
>>> print alist;print c
[1, 2, 3, ['a', 'b', 'cccc'], 5]
[1, 2, 3, ['a', 'b', 'cccc']] #里面的子对象被改变了

(3) Deep copy, including the copy of the self object in the object, so the change of the original object will not cause the change of any child elements in the deep copy

>>> import copy
>>> d=copy.deepcopy(alist)
>>> print alist;print d
[1, 2, 3, ['a', 'b']]
[1, 2, 3, ['a', 'b']] #始终没有改变
>>> alist.append(5)
>>> print alist;print d
[1, 2, 3, ['a', 'b'], 5]
[1, 2, 3, ['a', 'b']] #始终没有改变
>>> alist[3]
['a', 'b']
>>> alist[3].append("ccccc")
>>> print alist;print d
[1, 2, 3, ['a', 'b', 'ccccc'], 5]
[1, 2, 3, ['a', 'b']]  #始终没有改变

For safety reasons, try to use deep copy when you need to do copy operations.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325160866&siteId=291194637