我试图理解当我将列表(list1)分配到另一个变量(list2)并将第三个列表与(list3)连接时会发生什么。
list1 = [3,4]
list2=list1 # shallow copy/hard copy
list1 = list1 + [10,11]
print(list1)
print(list2)
If I apply the Shallow copy or Hard copy concept it should print
[3, 4, 10,10]
[3, 4, 10,11]
But in practice I get
[3, 4]
[3, 4, 10, 11]
Can anyone please explain what is happening in this code snippet? I use Python 3.6
答案 0 :(得分:0)
即使list1
和list2
是同一对象的两个名称(使用list1 is list2
确认),但在使用list1 = list1 + [10, 11]
添加其他列表时,实际上会创建一个新对象。如果您想就地修改list1
,请使用list1 += [10, 11]
。然后你会得到你所期望的。
答案 1 :(得分:-1)
据我所知,在浅拷贝的情况下,对象的引用被复制到其他对象中。这意味着对对象副本所做的任何更改都会反映在原始对象中,而在硬拷贝中,更改不会反映回原始对象,因此它取决于您使用的副本类型。