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 ran this code and expected this.
:0
0
:1
1
:2
2
:3
3
:4
4
:5
5
Instead I got this:
:0
0
:2
1
:4
2
Now I understand why this happened but is this an error in python? Shouldn’t it still go through all of the original objects instead of the length of the current list? And why did this not throw and out of bounds error?
IE: Shouldn’t it still have done:
:0
0
:1
2
:2
4
:3
Error
:4
Error
:5
Error
You are looping over a list and altering it at the same time. By using
.pop()you are shortening the list, but the iterator pointer is not updated.Use a copy instead:
or
where the
[:]slice notation returns a list copy.Another approach would be to use a
whileloop instead:because an empty list tests as boolean
False.The python
forloop uses it’s argument as an iterator, it does not itself keep an index. There is no way for theforloop to ‘know’ you removed elements. Instead, it’s thelist()iterator that keeps that pointer:That iterator keeps a counter, and every time you call
next()on the iterator it’ll give you the value at the next index, whatever that value may be, until the counter is equal to the current lenght of the list.