List as FIFO in for loop
"Martin v. Löwis"
martin at v.loewis.de
Sat Mar 8 17:44:12 CET 2008
> Still, why avoid changing loop variable? Does python treat looping
> over a list differently from looping over an iterator, where it
> doesn't know if the iterator future changes while loop running?
Take a look at Objects/listobject.c:listiterobject. It contains
an it_index, which is the index into the list of the current
So if you delete items with indices smaller than the iterator
index, the iterator index won't change, causing the iterator
to skip over elements, e.g.
for i in L:
Appending to lists will cause the new elements to
be iterated over later. Whether that's desirable or not depends
on the application. E.g. the following loop never terminates
for i in L:
Notice that the language specification *deliberately* does not
distinguish between deletion of earlier and later items, but
makes modification of the sequence undefined behavior to allow
alternative implementations. E.g. an implementation that would
crash, erase your hard disk, or set your house in flames if you
confront it with your code still might be a conforming Python
More information about the Python-list