Python For Loop List Interesting Result

前端 未结 4 1914
执念已碎
执念已碎 2021-01-25 07:42
a = [0,1,2,3,4,5]
for b in a:
  print \":\"+str(b)
  a.pop(0)

Thinking that this would work in order going through the entire list and all its items I

4条回答
  •  悲&欢浪女
    2021-01-25 08:24

    This is completely "expected" and documented behavior. When you iterate over the list, you're basically iterating over memory locations. When you pop something out of the list, everything after that in the list moves 1 index closer to the start of the list. Hence, you end up skipping items. Iteration stops when you reach the end of the list.

    Typically when doing something like this, you want to iterate over a copy of the list:

    for b in a[:]:
        ...
    

    As indicated in the comments, if you iterate over the list in reversed order:

    for b in reversed(a):
        a.pop()
    

    This works as intended because you are constantly pulling off the final element and therefore you're not shifting the position in the list of any of the elements that you haven't yet seen.

提交回复
热议问题