原始问题:下面的代码执行后为什么x的值是[2, 2]呢?
>>> x = [3, 5, 7]
>>> x = x[1:] = [2]
>>> x
[2, 2]
进一步,我们修改x列表的初始内容,会发现不管x的初始值是什么,执行x = x[1:] = [2]之后的x的值都是[2, 2]:
>>> x = [1, 2, 3, 3, 4, 5, 6]
>>> x = x[1:] = [2]
>>> x
[2, 2]
接下来我们重启Python shell,然后执行下面的代码:
>>> x = x[1:] = [2]
>>> x
[2, 2]
>>> del x
>>> x
Traceback (most recent call last):
File "<pyshell#49>", line 1, in <module>
x
NameError: name 'x' is not defined
>>> x = x[1:] = [2]
>>> x
[2, 2]
实际上这里有个小坑,这个问题的根源在于x = [1:] = [2]相当于x = [2]和x[1:] = [2]这两条语句,也就是说先创建列表x的值为[2],然后使用切片为其追加一个元素2,然后得到[2, 2]。