[英]Why does Python's "for" iterate the length of the list even if I change the length in the loop?
I came across this question using python.我使用 python 遇到了这个问题。
l = [1,2,3,4]
for i in l:
x = l.pop(0)
print(x)
l.insert(0,x)
And the result gives me 1,1,1,1
.结果给了我
1,1,1,1
。 I was wondering why this could happen?我想知道为什么会发生这种情况? Shouldn't I have infinite 1's?
我不应该有无限个 1 吗?
There is a point worth to pay attention to.有一点值得关注。 when your for loop start it navigate through your list, starting from the first item which is "1" in your list.
当您的 for 循环开始时,它会从您列表中的第一个“1”项开始浏览您的列表。 it pop ( remove the item) and print the removed item, after this stage you have 2,3.4 in your list.
它弹出(删除项目)并打印删除的项目,在此阶段之后,您的列表中有 2,3.4。 and finally you add the item you have removed back to your list.
最后,您将已删除的项目添加回您的列表。 when the loop execute again it does exactly what did before, in fact your "i" variable in the loop has finite values (1,2,3.4) and the code inside the loop repeat only 4 times!.
当循环再次执行时,它完全按照以前的方式执行,实际上循环中的“i”变量具有有限值(1,2,3.4)并且循环内的代码仅重复 4 次!。 I hope you get the point but if not let's trace your code as below
我希望你明白这一点,但如果没有,让我们按照下面的方式跟踪你的代码
i=1 x=1 print(1) l = [1,2,3,4]
i=2 x=1 print(1) l = [1,2,3,4]
i=3 x=1 print(1) l = [1,2,3,4]
i=4 x=1 print(1) l = [1,2,3,4]
add print(l) at the end of your code to see what exactly happens to your list for each "i" in your for loop.在代码末尾添加 print(l) 以查看 for 循环中每个“i”的列表到底发生了什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.