[Tutor] a question about list
Bill Mill
bill.mill at gmail.com
Fri Nov 12 06:56:04 CET 2004
On Thu, 11 Nov 2004 22:19:12 -0500, Kent Johnson <kent37 at tds.net> wrote:
> Max Noel wrote:
> >
> > On Nov 11, 2004, at 23:17, Terry Carroll wrote:
> > a = [element for index, element in enumerate(a) if index not in b]
> >
> > Looks a bit more Pythonic to me. I also think it's faster.
>
> Regular readers of this list know I can't resist an optimization
> challenge :-) Also I was suspicious of Max's claim, as this method is
> clearly O(len(a) * len(b)) at least - for each element of a, the list b
> is searched for the index.
>
Well, as you all probably know, I can't resist one either, and I think
I found a way to one-up all the given functions. I replaced remove2
since it was the loser and I'm lazy:
######
#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.
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?
Peace
Bill Mill
bill.mill at gmail.com
More information about the Tutor
mailing list