Deleting from a list while iterating
Rhamphoryncus
rhamph at gmail.com
Sun Dec 3 11:11:38 EST 2006
Marc 'BlackJack' Rintsch wrote:
> 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:
Fredrik Lundh wrote:
> your set approach doesn't modify the list in place, though; it creates
> a new list, in a rather roundabout way. if modification in place isn't
> important, the normal way is of course to create a *new* list:
>
> items = [i for i in items if not i < 0.5]
>
> on my machine, that's about two orders of magnitude faster than your
> "fast" approach for n=100000.
Sorry, I should have clarified that the original post assumed you
needed info from the "do something" phase to determine if an element is
removed or not. As you say, a list comprehension is superior if that
is not necessary.
--
Adam Olsen, aka Rhamphoryncus
More information about the Python-list
mailing list