How to del item of a list in loop?

Nick Coghlan ncoghlan at iinet.net.au
Sat Jan 15 11:27:00 EST 2005


Reinhold Birkenfeld wrote:
> Addition: In Py2.4, I can't find a problem with
> 
> for i in reversed(lst)

Some poking around suggests it's fine - and it avoids copying the list. Don't 
delete anything earlier in the list than the current element though (which 
list.remove() will do quite happily when data is duplicated).

However, there will still be data movement costs when deleting elements from the 
middle of the list. In addition, remove() itself has to do a linear search for 
the value being removed.

An off-place solution based on a list comprehension is usually going to be your 
best performer - it's an O(n) operation, based on the size of the original list. 
The in-place mechanisms can turn out to be O(n**2) due to worst-case memory 
movement effects (lists don't allow gaps, so deleting items will usually trigger 
data movement).

I think this is about the best you can do for an in-place version:
   for i, x in enumerate(reversed(lst)):
     if x == 2:
       del lst[-i]

The effbot's version is still going to be faster though:
   lst = [x for x in lst if x != 2]

Cheers,
Nick.


-- 
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net



More information about the Python-list mailing list