Removing items from a list in a loop
Andrew Henshaw
andrew.henshaw at gtri.gatech.edu
Wed Jun 21 03:22: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)
>
...snip...
>Is there a safe way to iterate through a list and remove some items?
>
If you can negate the sense of Function(x) such that Function(x) returns
false when you want to remove x and true otherwise, then you can use the very
fast 'filter' built-in:
list= filter(Function, list)
--
Andy Henshaw
More information about the Python-list
mailing list