Deleting from a list (reprise)

Hans Nowak wurmy at earthlink.net
Wed Jan 2 02:50:01 EST 2002


Anthony Baxter wrote:
> 
> >>> Hans Nowak wrote
> > >>> x = [1, 2, 3, 1, 2, 8, 3, 1, 1, 1, 6]
> > >>> while 1 in x:
> >       x.remove(1)
> > >>> x
> > [2, 3, 2, 8, 3, 6]
> > >>>
> 
> note that this is pretty inefficient, as it starts at the start of
> the list each time through the loop. 

Agreed. For small lists, the performance difference is trivial,
though. I made a silly little benchmark (not posted) that shows
that walking through the list backwards is almost always
faster than the 'while x in lst' method shown above. How much
faster depends on the frequency of the object-to-be-removed.

--Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==\n') 
       # decode for email address ;-)
Site:: http://www.awaretek.com/nowak/



More information about the Python-list mailing list