浅copy 与 深copy

时间:2023-12-14 17:41:02
 import copy
names = ["zhangyang", 'guyun', 'xiangpeng', ['jack','tom'], 'xuliangchen']
names2 = names.copy() #浅copy,复制后改变原列表,copy后的列表不发生改变 names[2] = "祥鹏"
names.append("zhangshan") print(names)
print(names2) names3 = copy.deepcopy(names)#深copy,copy后原列表改变,copy的列表也会发生同样改变
print('this is names3:', names3)

浅copy的三种实现方式:

 import copy

 names = ["zhangyang", 'guyun', 'xiangpeng', ['jack','tom'], 'xuliangchen']

 #第一种方式
names2 = copy.copy(names)
#第二种
names3 = names[:]
#第三种
names4 = list(names)