两个声明都产生相同的结果,但是我想知道幕后的区别是什么。
a = [1,2,3,4,5]
a[:] = a[0:3]
print(a)
a = [1,2,3,4,5]
a = a[0:3]
print(a)
答案 0 :(得分:1)
这可以用另一个变量更好地解释。
假设a和b相同。当我们使用切片分配时,a和b都会更改,因为它们是相同的列表。无需将其分配给均值切片,就可以创建一个新的列表,称为a,该列表与b不再相关。
a = b = [0, 1, 2]
a[:] = a[0:2]
# a and b point to the same object and that got changed
print(a) # gives [0, 1]
print(b) # gives [0, 1]
a = b = [0, 1, 2]
a = a[0:2]
# a and b point to two different objects sharing no memory together
print(a) # gives [0, 1]
print(b) # gives [0, 1, 2]