-
浅copy
>>> names = ['yuxin', 26]
>>> n = names
# 内存地址相同
>>> id(names),id(n)
(1319935610632, 1319935610632)
# copy后内存地址不同
>>> n2 = names.copy()
>>> id(names),id(n2)
(1319935610632, 1319935698568)
# copy后内部元素内存地址相同
>>> id(names[0]),id(n[0]),id(n2[0])
(1319935641224, 1319935641224, 1319935641224)
# 改变names 元素的值,names元素的内存地址改变,不影响 n2 的元素
>>> names[0] = 'YUXIN'
>>> names
['YUXIN', 26]
>>> n
['YUXIN', 26]
>>> n2
['yuxin', 26]
>>> id(names[0]),id(n[0]),id(n2[0])
(1319935640048, 1319935640048, 1319935641224)
>>> names = ['yuxin', 26, ['kkkk',777]]
>>> n = names.copy()
>>> id(names),id(n)
(1319935610696, 1319935625864)
>>> id(names[-1]),id(n[-1])
(1319935610376, 1319935610376)
'''
copy元素的内存是相同的,当列表里面包含子列表时,改变子列表的元素的值,不影响子列表的内存地址,所以names,n 子列表元素的值都改变
'''
>>> names[-1][0] = 'yyyy'
>>> names
['yuxin', 26, ['yyyy', 777]]
>>> n
['yuxin', 26, ['yyyy', 777]]
>>> id(names[-1]),id(n[-1])
(1319935610376, 1319935610376)
-
深copy
>>> import copy
>>> n3 = copy.deepcopy(names)
>>> n3
['yuxin', 26, ['yyyy', 777]]
>>> names
['yuxin', 26, ['yyyy', 777]]
#深copy是完完全全的copy,元素的内存地址不同,所以修改names 子列表的值,n3子列表的值不会改变
>>> id(names),id(n3)
(1319935610696, 1319935625928)
>>> id(names[-1]),id(n3[-1])
(1319935610376, 1319935698376)
>>> names[-1][0] = 'pppp'
>>> names
['yuxin', 26, ['pppp', 777]]
>>> n3
['yuxin', 26, ['yyyy', 777]]