When assigning values between objects in Python is passed by reference, the copy module in the standard library is required if the object needs to be copied.
1. Copy.copy a shallow copy copies only the parent object and does not copy the inner sub-objects of the object.
2. Copy.deepcopy deep copy Copy object and its sub-object Program:
Import copy a = [1, 2, 3, 4, [' A ', ' B ']] #原始对象 b = A #赋值, reference to the object C = copy.copy (a) #对象拷贝, shallow copy d = Copy.deepco PY (a) #对象拷贝, deep copy a.append (5) #修改对象a a[4].append (' C ') #修改对象a中的 [' A ', ' B '] Array object print ' A = ', a print ' B = ' , b print ' c = ', C
Output Result:
A = [1, 2, 3, 4, [' A ', ' B ', ' C '], 5]
b = [1, 2, 3, 4, [' A ', ' B ', ' C '], 5]
c = [1, 2, 3, 4, [' A ', ' B ', ' C ']]
D = [1, 2, 3, 4, [' A ', ' B ']]
Append reference assignment problem handling for list in Python