Extracting from a list

Huaiyu Zhu huaiyu at gauss.almadan.ibm.com
Wed Apr 10 20:05:43 EDT 2002


Daniel Dittmar <daniel at dittmar.net> wrote:
>Using .remove () is similar to scanning the list, so it doesn't buy you anything in terms of performance.
>
>
>How about:
>
>for i in xrange (len (lst) - 1, -1, -1):
>     item = lst [i]
>     if item < 5:
>         print item
>         del lst [i]
>
>This makes it possible to delete items from the list as the access is 
>back to front.

I've seen this several times in the past, in the context of making the loop
counter correct.  But how does it fare in terms of performance?  Does the
rest of the list get copied with each del?   This sounds like an O(nm)
operation, where n is the list length and m is the number of del's.

Huaiyu



More information about the Python-list mailing list