Deleting from a list while iterating
Fredrik Lundh
fredrik at pythonware.com
Sun Dec 3 11:25:47 EST 2006
Rhamphoryncus wrote:
> 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.
that's spelled
out = []
for i in items:
... do something ...
if i > 0.5:
out.append(i)
in Python, and is only a little slower than a list comprehension, as
written above. if performance is really important, move the method
lookup out of the loop:
out = []
append = out.append
for i in items:
... do something ...
if i > 0.5:
append(i)
</F>
More information about the Python-list
mailing list