In <[EMAIL PROTECTED]>, 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

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to