Why does a for-loop with pop-method (or del statement) not iterate over all list elements [duplicate]

Unrolling a bit (the caret (^) is at the loop “index”):

your_list = [1,2,3,4,5,6]
             ^

after popping off the first item:

your_list = [2,3,4,5,6]
             ^

now continue the loop:

your_list = [2,3,4,5,6]
               ^

Now pop off the first item:

your_list = [3,4,5,6]
               ^

Now continue the loop:

your_list = [3,4,5,6]
                 ^

Now pop off first item:

your_list = [4,5,6]
                 ^

Now continue the loop — Wait, we’re done. 🙂


>>> l = [1,2,3,4,5,6]
>>> for x in l:
...     l.pop(0)
... 
1
2
3
>>> print l
[4, 5, 6]

Leave a Comment

tech