1 #浅copy,第一层创建的是新的内存地址,而从第二层开始,指向的都是同一个内存地址 2 list1 = [1,2,[3,4]] 3 list2 = list1.copy() 4 print(list1,id(list1)) 5 print(list2,id(list2)) 6 7 list1[0]=3 8 print(list1,id(list1),id(list1[2])) 9 print(list2,id(list2),id(list2[2])) 10 11 list1[2][0] = 5 12 print(list1,id(list1),id(list1[2])) 13 print(list2,id(list2),id(list2[2])) 14 15 #深copy,两个是完全独立的,改变任意一个的任何元素(无论多少层),另一个绝对不改变 16 import copy 17 list1 = [1,2,[3,4]] 18 list2 = copy.deepcopy(list1) 19 20 print(list1,id(list1),id(list1[2])) 21 print(list2,id(list2),id(list2[2])) 22 23 list1[0] = 3 24 print(list1,id(list1),id(list1[2])) 25 print(list2,id(list2),id(list2[2])) 26 27 list1[2][0] = 5 28 print(list1,id(list1),id(list1[2])) 29 print(list2,id(list2),id(list2[2]))
[1, 2, [3, 4]] 2635642502984 [1, 2, [3, 4]] 2635643714248 [3, 2, [3, 4]] 2635642502984 2635643712648 [1, 2, [3, 4]] 2635643714248 2635643712648 [3, 2, [5, 4]] 2635642502984 2635643712648 [1, 2, [5, 4]] 2635643714248 2635643712648 [1, 2, [3, 4]] 2635643712520 2635643713288 [1, 2, [3, 4]] 2635642502984 2635643719880 [3, 2, [3, 4]] 2635643712520 2635643713288 [1, 2, [3, 4]] 2635642502984 2635643719880 [3, 2, [5, 4]] 2635643712520 2635643713288 [1, 2, [3, 4]] 2635642502984 2635643719880 Process finished with exit code 0