Modifying list while iterating [duplicate]

Never alter the container you’re looping on, because iterators on that container are not going to be informed of your alterations and, as you’ve noticed, that’s quite likely to produce a very different loop and/or an incorrect one. In normal cases, looping on a copy of the container helps, but in your case it’s clear that you don’t want that, as the container will be empty after 50 legs of the loop and if you then try popping again you’ll get an exception.

What’s anything BUT clear is, what behavior are you trying to achieve, if any?! Maybe you can express your desires with a while…?

i = 0
while i < len(some_list):
    print i,                         
    print some_list.pop(0),                  
    print some_list.pop(0)

Leave a Comment