deep copy

Copy: exactly the same after assignment, pointing to the memory space.
Shallow copy: After the first layer of nested data type is copied, it is completely two copies, changing one of them

 

l1 = [1,2,3,['barry','alex']] 

  Step 1: Copy l1 and assign it to l2 l2 = l1.copy()
to check the memory addresses of l1 and l2 The
phenomenon is that l1 and l2 are completely different print(l1,id(l1)) # [1, 2, 3, ['barry', 'alex']] 2380296895816 print(l2,id(l2)) # [1, 2, 3, ['barry', 'alex']] 2380296895048
Step 2: Modify the data of the first layer
Phenomenon: The memory addresses are still two completely different l1[1] = 222 print(l1,id(l1)) # [1, 222, 3, ['barry', 'alex']] 2593038941128 print(l2,id(l2)) # [1, 2, 3, ['barry', 'alex']] 2593038941896 The third step: modify the inner data
phenomenon: the memory address is still the same after modification l1[3][0] = 'wusir' print(l1,id(l1[3])) # [1, 2, 3, ['wusir', 'alex']] 1732315659016 print(l2,id(l2[3])) # [1, 2, 3, ['wusir', 'alex']] 1732315659016

 


Deep copy: no matter how many layers are the same after copying

l1 = [1,2,3,['barry','alex']]

l2
= l1.copy() print(l1,id(l1)) # [1, 2, 3, ['barry', 'alex']] 2380296895816 print(l2,id(l2)) # [1, 2, 3, ['barry', 'alex']] 2380296895048
l1[1] = 222
print(l1,id(l1)) # [1, 222, 3, ['barry', 'alex']] 2593038941128
print(l2,id(l2)) # [1, 2, 3, ['barry', 'alex']] 2593038941896
 
l1[
3][0] = 'wusir' print(l1,id(l1[3])) # [1, 2, 3, ['wusir', 'alex']] 1732315659016 print(l2,id(l2[3])) # [1, 2, 3, ['wusir', 'alex']] 1732315659016

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325339737&siteId=291194637