[Tutor] iterating over a changing list

Steven D'Aprano steve at pearwood.info
Thu Oct 11 03:50:50 CEST 2012


On 11/10/12 08:49, eryksun wrote:

> Also, generally avoid mutating a list while iterating over it.
> listiterator is just incrementing an index, so modifying the size of
> the list can produce nonsense (e.g. if you remove the current item,
> the next item will be skipped). Instead, create an empty list and
> append() to it.


If you absolutely have to modify the list you are iterating over,
iterate over it backwards:


# this doesn't work correctly
for i in range(len(mylist)):
     x = mylist[i]
     if x < 0:
         del mylist[i]


# this does
for i in range(len(mylist)-1, -1, -1):
     x = mylist[i]
     if x < 0:
         del mylist[i]


But really, don't do that either. Iterate over a copy, or make
a new list with the items you want. It's faster and easier.



-- 
Steven


More information about the Tutor mailing list