简体   繁体   English

为什么即使我在循环中更改长度,Python 的“for”也会迭代列表的长度?

[英]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.

相关问题 为什么我的循环不迭代整个长度? - Why does my loop not iterate the whole length? 为什么每次运行此循环时列表长度都会改变,在 Python 中,只存储偶数? - Why is the list length changing every time I run this loop, in Python, to only store even numbers? Python - 如果我增加列表的大小,为什么我的 for 循环的长度 function 不会改变 - Python - Why doesn't the length function change for my for loop if I'm increasing the size of a list 为什么For循环会产生可变列表长度 - Why does the For loop produce variable list length 如何在Python中以未知长度的列表迭代级联格式(在for循环中)? - How do I iterate in a cascaded format (in a for loop) over a list of unknown length in Python? 为什么我的长度为 1 的字符串变为长度为 3? - Why does my string of length 1 change to length 3? 如何在循环和更改列表长度内过滤Python 3中的数字列表 - how to filter a numbers list in Python 3 inside a loop & change list length 为什么我的列表长度必须包含 -1 才能在我的 for 循环中容纳 +1? - Why does the length of my list have to include -1 to accomodate a +1 in my for loop? 为什么 Flask 迁移没有检测到字段的长度变化? - Why Flask Migrations does not detect a field's length change? Python列表理解甚至字符串长度 - Python list comprehension even string length or not
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM