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 simply copies the object's reference.
1. Assigning Values
The assignment is actually just passing the object reference, and the Reference object ID is the same. The original list changes, and the assigned B also makes the same change.
>>> alist=[1,2,3,["A", "B"]]>>> b=list>>> print (b) [1, 2, 3, [' A ', ' B ']]>>> List.append (5) >>> alist=[1,2,3,["A", "B"]]>>> b=alist>>> print (b) [1, 2, 3, [' A ', ' B ']]> >> alist.append (5) >>> print (alist);p rint (b) [1, 2, 3, [' A ', ' B '], 5][1, 2, 3, [' A ', ' B '], 5]
2. Shallow copy
A shallow copy is a reference to a copy of a primitive object element, in other words, a shallow copy produces a new object, but its contents are not new but a reference to the original object.
>>> Import copy>>> alist=[1,2,3,["A", "B"]]>>> C = copy.copy (alist) >>> print (alist );p rint (c) [1, 2, 3, [' A ', ' B ']][1, 2, 3, [' A ', ' B ']]>>> alist.append (5) >>> print (alist);p rint (c) [1, 2, 3 , [' A ', ' B '], 5][1, 2, 3, [' A ', ' B ']]>>> alist[3][' A ', ' B ']>>> alist[3].append (' CCCC ') >>> prin T (alist);p rint (c) [1, 2, 3, [' A ', ' B ', ' CCCC '], 5][1, 2, 3, [' A ', ' B ', ' CCCC ']] #里面的子对象被改变了
Several ways to light copy:
- Copy using the slice [:] Operation
>>> alist = [1,2,3,["A", "B"]]>>> C = alist[:]>>> print (c) [1, 2, 3, [' A ', ' B ']]
- Use factory functions (such as list/dir/set) for copying
>>> alist = [1,2,3,["A", "B"]]>>> c = List (alist) >>> print (c) [1, 2, 3, [' A ', ' B ']]
- Copy.copy ()
>>> alist = [1,2,3,["A", "B"]]>>> C = copy.copy (alist) >>> print (c) [1, 2, 3, [' A ', ' B ']]
3. Deep copy
A deep copy is a complete copy of the original object, and the resulting object is new and unaffected by the operation of other referenced objects.
Deep copy:
Names2 = copy.deepcopy(names)
>>> Import copy>>> alist=[1,2,3,["A", "B"]]>>> d=copy.deepcopy (alist) >>> print ( alist);p rint (d) [1, 2, 3, [' A ', ' B ']][1, 2, 3, [' A ', ' B ']] always unchanged >>> 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 ("cc CCC ") >>> print (alist);p rint (d) [1, 2, 3, [' A ', ' B ', ' CCCCC '], 5][1, 2, 3, [' A ', ' B ']] never changed
Python Learning notes-(vi) deep copy& shallow copy