Python中'for a[-1] in a'和'for a in a'的区别?

Difference between 'for a[-1] in a' and 'for a in a' in Python?

在此 中,以下代码片段可能有效。

a = [0, 1, 2, 3]
for a[-1] in a:
    print(a[-1])

参考这个

While doing for a[-1] in a, you actually iterate through the list and temporary store the value of the current element into a[-1].

同样,我认为做for a in a,它应该遍历列表并将当前元素的值临时存储到a,所以a的值可能是0,且不可迭代,则下一次迭代会抛出TypeError异常。然而,结果如下。

>>> a = [0, 1, 2, 3]
>>> for a in a:
...     print a
... 
0
1
2
3
>>> a
3

如何理解?

引用 official documentation on for loop,

An iterator is created for the result of the expression_list. The suite is then executed once for each item provided by the iterator, in the order of ascending indices.

因此,当您迭代一个对象时,会创建一个迭代器对象并用于迭代。这就是为什么原始对象不会丢失,至少在循环运行之前不会丢失。

在您的例子中,当执行 for a in a: 时,首先为 a 创建一个迭代器对象,然后从迭代器对象中检索值。即使循环在每次迭代中将名称 a 绑定到某个其他值,迭代器对象仍然持有对原始列表对象的引用,并从中给出值。这就是您没有收到任何错误的原因。