不同的是,当你使用a[:] = b它意味着你将覆盖已经存在的任何东西a.如果你有别的东西,a它的引用也会改变,因为它不断引用相同的位置.
另一方面,a = b[:]创建一个新引用并将所有值复制b到此新引用.因此,对旧数据的现有引用将继续指向旧数据.
考虑这个例子:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a # c is a reference to the list in a
>>> c
[1, 2, 3]
>>>
>>> a[:] = b
>>> a # a will have a copy of the list in b
[4, 5, 6]
>>> c # and c will keep having the same value as a
[4, 5, 6]
>>>
>>> b = [7, 8, 9]
>>> a = b[:]
>>> a # a has the new value
[7, 8, 9]
>>> c # c keeps having the old value
[4, 5, 6]
Run Code Online (Sandbox Code Playgroud)