First of all, we know that in Python3, there are six standard data types, and they’re divided into mutable and immutable.
- Immutable: Number, String, Tuple.
- You can change: List, Dictionary, Set.
Shallow copy
A and B are independent objects, but their child objects still refer to the same object. After a shallow copy, changing the value of the mutable element in the original object will affect the copied object at the same time. Changing the value of an immutable element in the original object does not affect the copied object.
The first element is mutable >>> A = [[1,2],'fei',90]# shallow copy
>>> B = copy.copy(A)Object addresses are the same
>>> A is B
FalseIs the address of the first element the same
>>> A[0] is B[0]
TrueIs the address of the second element the same
>>> A[1] is B[1]
True# change the value of the first mutable type to see how the copied object changes
>>> A[0] [0] = 2
>>> A
[[2.2].'fei'.90]The copy object is also changed
>>> B
[[2.2].'fei'.90]# Change the value of the second immutable type to see how the copied object changes
>>> A[1] = 'anne'
>>> A
[[2.2].'anne'.90]The copied object is not changed
>>> B
[[2.2].'fei'.90]
Copy the code
Deep copy
A and B copy the parent object and its child object completely independently. Deep copy, in addition to the top copy, also copies the child elements. After deep copy, all mutable element addresses of the original object and the copied object are not the same.
C = copy. Deepcopy (A
>>> A is C
FalseIs the address of the first element the same
>>> A[0] is C[0]
FalseIs the address of the second element the same
>>> A[1] is C[1]
True# Change the first element to see the duplicate element changes
>>> A[0] [0] = 2
>>> A
[[2.2].'fei'.90]The copied elements will not change
>>> C
[[1.2].'fei'.90]
# Change the second element to see the duplicate element changes
>>> A[1] = 'Anne' >>> A[[2.2].'Anne'.90]
The copied elements will not change
>>> C[[1.2].'fei'.90]
Copy the code
I see A puzzle here, A is B
Assignment reference
A and B both refer to the same object
#Python Learning Exchange group: 531509025
# Assignment reference
>>> A = [[1.2].'fei'.90]
>>> D = A
Object addresses are the same
>>> A is D
True
Is the address of the first element the same
>>> A[0] is D[0]
True
Is the address of the second element the same
>>> A[1] is D[1]
True
Change the first element in A to see if it affects D
>>> A[0] [0] = 2
>>> A
[[2.2].'fei'.90]
The first element in #D is also changed
>>> D
[[2.2].'fei'.90]
Change the second element in D to see if it affects A
>>> D[1] = 'anne'
The second element in #A has also changed
>>> A
[[2.2].'anne'.90]
>>> D
[[2.2].'anne'.90] > > >Copy the code