iterating through lists to delete elements

Skip Montanaro skip at pobox.com
Thu Aug 9 12:45:14 EDT 2001


    Mark> Can anyone advise me the best way to iterate through a list and
    Mark> deleting elements that don't meet a certain criteria.

I typically traverse the list backwards:

    for i in range(len(list)-1,-1,-1):
        if list[i] > y:
            del list[i]

It's fairly easy to recognize because to range over a list front-to-back you
use

    range(len(list))

and to range over a list back-to-front you add "-1,-1,-1" between the two
closing parens:

    range(len(list)-1,-1,-1)

-- 
Skip Montanaro (skip at pobox.com)
http://www.mojam.com/
http://www.musi-cal.com/




More information about the Python-list mailing list