Deleting from a list while iterating

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Sun Dec 3 10:50:19 EST 2006


In <1165160235.282030.96610 at 79g2000cws.googlegroups.com>, Rhamphoryncus
wrote:

> My approach is to make a set of indexes to removed while iterating,
> then use a list comprehension to filter them out after.  Timings of
> this and two other common approaches follow:
> 
> setapproach = """\
> def func(count):
>     from random import random
>     items = [random() for i in xrange(count)]
>     remove = set()
>     for index, x in enumerate(items):
>         #...do something...
>         if x < 0.5:
>             remove.add(index)
>     items = [x for index, x in enumerate(items) if index not in remove]
> """

Why do you make it that complicated?  If you are going to build a new list
anyway, this can be done without the `set()` and just one listcomp:

  items = [x for x in items if x < 0.5]

No need to iterate twice over the `items`.  The two other approaches you
gave are just needed if it's important that the elements are deleted "in
place", i.e. that you don't rebind `items` to a new object.

Ciao,
	Marc 'BlackJack' Rintsch




More information about the Python-list mailing list