Most efficient solution?

Skip Montanaro skip at
Mon Jul 16 17:24:36 EDT 2001

    Jay> I've never noticed the list behaviour before that you pointed out,
    Jay> what causes that, if you don't mind my asking?

When you execute something like

    for elt in somelist:
        yadda(elt, yadda, yadda)

the for loop keeps an index into the list (internally - you can't access it)
and calls


as you traverse the list (ignore the upcoming iterator stuff).  If you
change the parts of the list you haven't yet visited there is no way to
convey this to the for loop.  If the list might change as you are traversing
it the normal Python idiom is to traverse the list back-to-front:

    for i in range(len(somelist)-1, -1, -1):
        elt = somelist[i]
        yadda(elt, yadda, yadda)

Skip Montanaro (skip at

More information about the Python-list mailing list