list.pop 在 for 循环中不会弹出最后一个元素

list.pop inside a for loop doesn't pop the last elements

代码:

stack = ['BOB','TOM','JAI','ALI','OM']
print(stack)

for i in stack:
    stack.pop()

print(stack)

输出:

['BOB', 'TOM', 'JAI', 'ALI', 'OM']
['BOB', 'TOM']

为什么弹出最后3个元素后停止?该列表还剩下 2 个元素,但由于某种原因它不起作用

那是因为您在遍历列表时修改了列表。

如果第一次迭代,Python 获取列表索引 0 处的项目,
如果第二次迭代,Python 获取列表索引 1 处的项目,
等等

Python 用于获取项目的隐式计数器变量正在递增...

在每次迭代中打印您的列表以查看其中的内容:

stack = ['BOB', 'TOM', 'JAI', 'ALI', 'OM']

for i in stack:
    print(stack)
    stack.pop()

print(stack)

输出:

['BOB', 'TOM', 'JAI', 'ALI', 'OM']
['BOB', 'TOM', 'JAI', 'ALI']
['BOB', 'TOM', 'JAI']
['BOB', 'TOM']

所以 :

In first iteration --> idx = 0 --> ['BOB', 'TOM', 'JAI', 'ALI', 'OM']
In second iteration --> idx = 1 --> ['BOB', 'TOM', 'JAI', 'ALI']
In third iteration --> idx = 2 --> ['BOB', 'TOM', 'JAI']
In forth iteration --> idx = 3 --> ['BOB', 'TOM'] --> Exit the loop here.

解决方案:

for i in stack.copy(): # Now you are iterating over a "copy" of the list
    stack.pop()

你也可以这样做:

for _ in range(len(stack)):
    stack.pop()