Deleting from a list

Skip Montanaro skip at pobox.com
Tue Jan 1 22:16:22 EST 2002


    Bob> ... I tried:

    Bob>        for i in len(lines):
    Bob>                l=lines[i]
    Bob>                ...
    Bob>                if ...:
    Bob>                        lines.pop(i)

    Bob> and this causes problems since 'i' can now point to out of range
    Bob> lines.

Try walking backward through the list:

    for i in range(len(lines)-1,-1,-1):
        if something:
            del lines[i]

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




More information about the Python-list mailing list