[英]Why does the for loop behave differently than the while loop for the “pop” function?
I have the following list:我有以下列表:
list1=['pic1','pic2', 'pic3']
The loop below iterates through the list:下面的循环遍历列表:
n=0
for item in list1:
nose= list1.pop(n)
print(nose)
Output: Output:
pic1
pic2
Why doesn't the last item in the list get printed in the for loop, but the while loop prints all three items:为什么列表中的最后一项没有在 for 循环中打印,但 while 循环打印所有三个项:
n=0
while len(list1)>0:
nose= list1.pop(n)
print(nose)
Output: Output:
pic1
pic2
pic3
You can test the first program to see what it's doing with a print statement:您可以测试第一个程序以查看它对 print 语句的作用:
list1=['pic1','pic2', 'pic3']
n=0
for item in list1:
nose= list1.pop(n)
print(f'{list1}, item={item}, popped={nose}')
First time through the loop, item
contains pic1
, the value at index 0, it pops it and prints it:第一次通过循环, item
包含pic1
,索引 0 处的值,它弹出并打印它:
['pic2', 'pic3'], item=pic1, popped=pic1
Second time through the loop, it prints:第二次通过循环,它打印:
['pic3'], item=pic3, popped=pic2
That is, it moved the index of the loop to position 1, which is now pic3
as you already popped an entry from the list on the previous iteration.也就是说,它将循环的索引移动到 position 1,现在是pic3
,因为您已经在上一次迭代中从列表中弹出了一个条目。 It pops the pic2
from the list.它从列表中弹出pic2
。
Now the loop is finished.现在循环结束了。 The index of the next item is beyond the end of the list, so it stops.下一项的索引超出了列表的末尾,因此它停止了。
As has been said in the comments, the basic rule is to never modify a list that you're iterating over, as it can have complex and unexpected (to the developer) results.正如评论中所说,基本规则是永远不要修改您正在迭代的列表,因为它可能会产生复杂且意外的(对开发人员而言)结果。
I observe that in below code you are always passing index 0 for pop()
method.我观察到在下面的代码中,您总是为pop()
方法传递索引 0。
list1.pop(n) where n=0
If you don't pass index to pop()
then it will remove the last element in the list.如果您不将 index 传递给pop()
那么它将删除列表中的最后一个元素。
Syntax句法
**list.pop(pos)**
pos => Optional. pos =>可选。 A number specifying the position of the element you want to remove, default value is -1,which returns the last item .一个数字,指定要删除的元素的 position,默认值为 -1,返回最后一项。
In while loop, since you are passing 0
index to pop()
method it will always remove items at 0
index and lenth of the list is 3 so it will print all three items.在 while 循环中,由于您将0
索引传递给pop()
方法,因此它将始终删除0
索引处的项目,并且列表的长度为 3,因此它将打印所有三个项目。
for item in list1:
nose= list1.pop()
print(nose)
while len(list1)>0:
nose= list1.pop()
print(nose)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.