Removing items from a list in a loop

Thaddeus L. Olczyk olczyk at interaccess.com
Tue Jun 20 19:32:34 EDT 2000


I would like to remove a bunch of items from a list *efficiently*.
Essentially  I would like to do this:

   for x in list:
        if Function(x):
	list.remove(x)

This does not work. Presumably for this reason:

list before removal
x1 x2 x3 x4 x5 

asume that both x2 and x3 need to be removed.

during removal
x1 x2 x3 x4 x5
     ^==x in loop

when removal done
x1 x3 x4 x5
     ^
next loop
x1 x3 x4 x5
          ^ skipping x3

Is there a safe way to iterate through a list and remove some items?




More information about the Python-list mailing list