The difference between python deep copy and shallow copy

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

There are generally three methods,

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

 

(1) Direct assignment, the default shallow copy transfers 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-objects are copied, so the original data changes, the sub-objects 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']] The child objects inside have been changed

 

 

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

>>> import copy

>>> d=copy.deepcopy(alist)
>>> print alist;print d
[1, 2, 3, ['a','b']]
[1, 2, 3, ['a','b ']] never changed
>>> alist.append(5)
>>> print alist;print d
[1, 2, 3, ['a','b'], 5]
[1, 2, 3, [ 'a','b']] never changed
>>> alist[3]
['a','b']
>>> alist[3].append("ccccc")
>>> print alist;print d
[1, 2, 3, ['a','b','ccccc'], 5]
[1, 2, 3, ['a','b']] remains unchanged

 

 /******************************************************************************************************************/

I have seen an interview question before, which is quite interesting, the output test returns true or false

Investigation points: 1. The difference between deep copy and shallow copy of immutable original group and variable list

         

 

 

 

Guess you like

Origin blog.csdn.net/sichuanpb/article/details/114961504