List as FIFO in for loop

"Martin v. Löwis" martin at v.loewis.de
Sat Mar 8 11:44:12 EST 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
iterator position.

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.

L=range(10)
for i in L:
   print i
   del L[0]

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

L=range(10:
for i in L:
   L.append(i)

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
implementation.

Regards,
Martin



More information about the Python-list mailing list