How to del item of a list in loop?
sjmachin at lexicon.net
Sun Jan 16 02:29:44 CET 2005
Michael Hoffman wrote:
> skull wrote:
> > but I still have an other thing to worry about coming with this
> > performance sucks when the list is big enough?
> > It makes a copy operation!
> > here is a faster and 'ugly' solution:
> > lst = [1, 2, 3]
> > i = 0
> > while i < len(lst):
> > if lst[i] == 2:
> > lst.remove(i)
> > else:
> > i += 1
> Actually, that is the slowest of the three methods proposed so far
> large lists on my system.
Assuming, as have other posters, that the requirement is to remove all
elements whose value is 2: it doesn't work. The result is [2, 3]
instead of the expected [1, 3].
> method_while: [3.8680000305175781, 3.8680000305175781,
Three significant figures is plenty. Showing just the minimum of the
results might be better.
> If you want to get really hairy, you can compare the bytecode
> for these three methods:
Timing and bytecode-peeking a broken function are a little "premature".
More information about the Python-list