[Tutor] a question about list

Kent Johnson kent37 at tds.net
Fri Nov 12 11:56:06 CET 2004

Bill Mill wrote:
> On Thu, 11 Nov 2004 22:19:12 -0500, Kent Johnson <kent37 at tds.net> wrote:
> ######
> #snip the top of Kent's file
> def remove2(a, b):
>     b.sort()
>     b.reverse()
>     for i in b:
>         a.pop(i)
> #snip the bottom of it too
> #######
> And the results:
> In [7]: @run test
> remove1: 0.028097 secs
> remove4: 0.026908 secs
> remove3: 0.004299 secs
> So, the builtin list.pop method appears to be the fastest.

Strange, in my testing it is slower to use a.pop(i) than del a[i]; i.e. 
your remove2 above is slower than my remove1. I tried both Python 2.3.4 
and Python 2.4 on Win2k. Are you sure you read the results correctly? 
(When the function name in the results is different from the name in the 
presented code I have to wonder...)

> By the by, the built-in list.remove function is horribly slow for this
> task, I found. I *guess* it's because a.remove(a[i]) has an extra list
> access, but that doesn't explain a time of .7 secs on this test.
> Anybody got a guess why?

a.remove(a[i]) is removing by _value_, not by index. So it has to search 
the list for the value to be removed. This is very slow compared to del 
a[i] which goes right to the correct spot in the list.


> Peace
> Bill Mill
> bill.mill at gmail.com

More information about the Tutor mailing list