Two, depth copy
1, first look at the assignment operation.
L1 = [1,2,3,[' Barry ', ' alex ']]l2 = l1l1[0] = 111print (L1) # [111, 2, 3, [' Barry ', ' Alex ']]print (L2) # [111, 2, 3, [ ' Barry ', ' Alex ']]l1[3][0] = ' wusir ' Print (L1) # [111, 2, 3, [' Wusir ', ' Alex ']]print (L2) # [111, 2, 3, [' Wusir ', ' al ' Ex ']]
For an assignment operation, L1 and L2 point to the same memory address, so they are exactly the same.
2, shallow copy copy.
L1 = [1,2,3,[' Barry ', ' Alex ']
L2 = L1.copy () print (L1,id (L1)) # [1, 2, 3, [' Barry ', ' Alex ']] 2380296895816print (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 ']] 1732315659016print (L2,id (l2[3])) # [1, 2, 3, [' Wusir ', ' Alex '] 1732315659016
For shallow copy, the first layer creates a new memory address, and from the second level it points to the same memory address, so consistency is maintained for the second layer and the deeper layers.
3, deep copy deepcopy.
Import COPYL1 = [1,2,3,[' Barry ', ' alex ']]l2 = copy.deepcopy (L1) print (L1,id (L1)) # [1, 2, 3, [' Barry ', ' Alex ']] 2915377 167816print (L2,id (L2)) # [1, 2, 3, [' Barry ', ' Alex ']] 2915377167048l1[1] = 222print (L1,id (L1)) # [1, 222, 3, [' Bar Ry ', ' Alex ']] 2915377167816print (L2,id (L2)) # [1, 2, 3, [' Barry ', ' Alex ']] 2915377167048l1[3][0] = ' wusir ' Print (L1, ID (l1[3]) # [1, 222, 3, [' Wusir ', ' Alex ']] 2915377167240print (L2,id (l2[3])) # [1, 2, 3, [' Barry ', ' Alex ']] 291537 7167304
For deep copy, the two are completely independent, changing any element of any one (no matter how many layers), and the other absolutely does not change.
The depth copy in Python