Python For循环列表有趣的结果

gab*_*eio 1 python python-2.7

a = [0,1,2,3,4,5]
for b in a:
  print ":"+str(b)
  a.pop(0)
Run Code Online (Sandbox Code Playgroud)

认为这将按顺序遍历整个列表及其所有项目,我运行此代码并期望这一点.

:0
0
:1
1
:2
2
:3
3
:4
4
:5
5
Run Code Online (Sandbox Code Playgroud)

相反,我得到了这个:

:0
0
:2
1
:4
2
Run Code Online (Sandbox Code Playgroud)

现在我明白为什么会发生这种情况,但这是python中的错误吗?它不应该仍然通过所有原始对象而不是当前列表的长度?为什么这不会抛出并超出界限错误?IE:它还不应该做到:

:0
0
:1
2
:2
4
:3
Error
:4
Error
:5
Error
Run Code Online (Sandbox Code Playgroud)

mgi*_*son 5

这完全是"预期的"并记录在案的行为.当您遍历列表时,您基本上是在内存位置上进行迭代.当您从列表中弹出一些内容时,列表中的所有内容会将1个索引移动到更靠近列表开头的位置.因此,您最终会跳过项目.到达列表末尾时,迭代停止.

通常在执行此类操作时,您希望迭代列表的副本:

for b in a[:]:
    ...
Run Code Online (Sandbox Code Playgroud)

如注释中所示,如果以相反的顺序迭代列表:

for b in reversed(a):
    a.pop()
Run Code Online (Sandbox Code Playgroud)

这是按预期工作的,因为你不断地拉出最后一个元素,因此你不会移动你尚未看到的任何元素列表中的位置.