Write in front:
. Copy () copies and [:] copies in Python are shallow copies
In Python, an object assignment is actually a reference to an object. When you create an object and then assign it to another variable, Python does not copy the object, but only copies the reference to the object.
There are generally three ways to
eg:alist=[1,2,3,["a","b"]]
(1) Direct assignment, passing the reference of the object, the original list is changed, and the assigned B will make the same change.
>>> b=alist>>>print b[123, [‘a‘‘b‘]]>>> alist.append(5)>>>print alist;print b[123, [‘a‘‘b‘5][123, [‘a‘‘b‘5]
(2) Copy shallow copy, no sub-object copied, so the original data changes, the sub-object will change
>>> ImportCopy>>>C=Copy.copy (alist)>>> PrintAlist;Printc[1,2,3, [' A ',' B ']][1,2,3, [' A ',' B ']]>>>Alist.append (5)>>> PrintAlist;Printc[1,2,3, [' A ',' B '],5][1,2,3, [' A ',' B ']]>>>alist[3][' A ',' B ']>>>alist[3].append (' CCCC ')>>> PrintAlist;Printc[1,2,3, [' A ',' B ',' CCCC '],5][1,2,3, [' A ',' B ',' CCCC ']]#里面的子对象被改变了
(3) A deep copy that contains a copy of the object inside the object, so the change of the original object will not cause any changes in the deep copy of any child elements
>>> ImportCopy>>>D=Copy.deepcopy (alist)>>> PrintAlist;Printd[1,2,3, [' A ',' B ']][1,2,3, [' A ',' B ']]#始终没有改变>>>Alist.append (5)>>> PrintAlist;Printd[1,2,3, [' A ',' B '],5][1,2,3, [' A ',' B ']]#始终没有改变>>>alist[3][' A ',' B ']>>>alist[3].append ("CCCCC")>>> PrintAlist;Printd[1,2,3, [' A ',' B ',' CCCCC '],5][1,2,3, [' A ',' B ']]#始终没有改变
For security reasons, use a deep copy when copying is required.
Python copy, deep copy and shallow copy difference