First, assign a value
>>>='hello'>>>='hello'>>>= a>>> [idforin (a,b,c)][426542164265421642654216]
A,b,c is the same as the address of the three, equivalent to A=b=c. The assignment system allocates memory to the variable or object (hello here) and assigns the address to the a,b,c. So their address is the same.
>>>='world'>>> [idforin (a,b,c)][426543844265421642654216]>>>print(a,b,c)world hello hello
At this point only the address and value of a change, but the B,c address and value are not changed. Because of the immutability of STR, a re-assignment requires a re-opening of the memory space, so the value of a changes, and a points to address changes. b, c because of ' hello ' invariance, will not change.
>>>= ['hello']>>>= ['hello']>>>= a>>> [idforin (a,b,c)][426709204267181642670920]
But this is not the case, the address of A and B are different. Why?
Because STR is immutable, it is also ' hello ' with only one address, but the list is mutable, so two addresses must be assigned.
>>> a[0='world'>>> [idforin (a,b,c)][426709204267181642670920]>>>print(a,b,c)['world'] ['hello'] ['world']
At this point the value and address of the a,c change, but the two are still the same, B does not change. Because of the variability of the list, changing the value of the list does not require additional space, just modify the value of the original address. So the a,c are changed.
Second, shallow copy and deep copy
import= [1,2,3,4,['a','b'#原始对象=#赋值=#浅拷贝=#深拷贝a.append(5)a[4].append('c')print('a = ',a)print('b = ',b)print('c = ',c)print('d = ',d)
a = [1 , 2 , 3 , 4 , [ ' a ' , ' B ' , ' C ' ], 5 ]b = [1 , Span class= "DV" >2 , 3 , 4 , [ ' a ' , ' B ' , ' C ' ], 5 ]c = [1 , 2 , 3 , 4 , [ ' a ' , ' B ' , ' C ' ]]d = [1 , 2 , 3 , 4 , [ ' a ' , ' B ' ]]
- Copy.copy a shallow copy copies only the parent object and does not copy the inner child objects of the object.
- Copy.deepcopy deep Copy Copy objects and their sub-objects
Summarize:
Assignment is to assign the address of an object to a variable, so that the variable points to that address (old bottles of old wine).
A shallow copy creates a new variable or container in another address, but the address of the element within the container is a copy of the address of the element of the source object. This means that the new container points to the old element (new bottle of old wine).
A deep copy is a new variable or container created in another address, and the address of the element inside the container is also newly opened, just the same value, which is a complete copy. That means (new bottle of new wine).
The difference between a python assignment, a shallow copy, and a deep copy