Removing items from a list in a loop
Bjorn Pettersen
bjorn at roguewave.com
Tue Jun 20 19:57:20 EDT 2000
"Thaddeus L. Olczyk" wrote:
>
> 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:
[snip]
the obvious way:
for x in list[:]: # create a copy
if f(x):
list.remove(x)
perhaps faster:
for i in range(len(list)-1, 0, -1):
x = list[i]
if f(x):
list.remove(x)
that traverses the list backwards, so should be more resistant to the
list changing...
-- bjorn
More information about the Python-list
mailing list