Introduction: First we have an assignment operation as a primer, as follows
1L1 = [1, 2, 3, ['Java','python']]2L2 =L13L1[0] = 1114 Print(L1)#output results: [111, 2, 3, [' Java ', ' Python ']]5 Print(L2)#output results: [111, 2, 3, [' Java ', ' Python ']]6 #from the above example, it is not difficult to understand that in Python for assignment operations, L1 and L2 point to the same address, so they are exactly the same.
1. Shallow copy copy ()
1L1 = [1, 2, 3, ['Java','python']]2L2 =l1.copy ()3 Print(L1,id (L1))#output results: [1, 2, 3, [' Java ', ' Python ']] 465946484 Print(L2,id (L2))#output results: [1, 2, 3, [' Java ', ' Python ']] 468617285 6L1[2] = 2227 Print(L1,id (L1))#output results: [1, 2, 222, [' Java ', ' Python ']] 465946488 Print(L2,id (L2))#output results: [1, 2, 3, [' Java ', ' Python ']] 468617289 TenL1[1] = 333 One Print(L1,id (L1))#output results: [1, 333, 222, [' Java ', ' Python ']] 86112856 A Print(L2,id (L2))#output results: [1, 2, 3, [' Java ', ' Python ']] 86707576 - -L1[3][0] ='C + +' the Print(L1,id (L1))#output results: [1, 333, 222, [' C + + ', ' python ']] 88013360 - Print(L2,id (L2))#output results: [1, 2, 3, [' C + + ', ' python ']] 88608080 -#对于浅拷贝来说, the first layer creates a new address, but the second layer is different, and the input changes affect the change of the copy item.
2. Deep copy Deepcopy
1 ImportCopy2L1 = [1, 2, 3, ['Java','python']]3L2 =copy.deepcopy (L1)4 5 Print(L1,id (L1))#output results: [1, 2, 3, [' Java ', ' Python ']] 570421046 Print(L2,id (L2))#output results: [1, 2, 3, [' Java ', ' Python ']] 570430247 8L1[2] = 2229 Print(L1,id (L1))#output results: [1, 2, 222, [' Java ', ' Python ']] 57042104Ten Print(L2,id (L2))#output results: [1, 2, 3, [' Java ', ' Python ']] 57043024 One AL1[1] = 333 - Print(L1,id (L1))#output results: [1, 333, 222, [' Java ', ' Python ']] 57042104 - Print(L2,id (L2))#output results: [1, 2, 3, [' Java ', ' Python ']] 57043024 the -L1[3][0] ='C + +' - Print(L1,id (L1))#output results: [1, 333, 222, [' C + + ', ' python ']] 57042104 - Print(L2,id (L2))#output results: [1, 2, 3, [' Java ', ' Python ']] 57043024#对于深拷贝deepcopy来说, no matter how many are created, each of these is independent, changing any element,
#都不会影响到其他的, no matter how many layers are the same
Copy and deepcopy in Python