While we're talking about annoyances

A

Alex Martelli

Michael Hoffman said:
Right. Using sort(key=keyfunc) is supposed to be faster than
decorate-sort-undecorate. And I think it is clearer too.

Right, and speed comparisons are pretty easy (just make sure to copy the
list within the loop to compare like with like:)...:

brain:~ alex$ python -mtimeit -s'L=range(-3,5)' 'X=L[:]; X.sort(lambda
x, y: cmp(abs(x), abs(y)))'
100000 loops, best of 3: 13 usec per loop

brain:~ alex$ python -mtimeit -s'L=range(-3,5)' 'X=[(abs(x),x) for x in
L]; X.sort(); X=[x for _,x in X]'
100000 loops, best of 3: 7.85 usec per loop

brain:~ alex$ python -mtimeit -s'L=range(-3,5)' 'X=L[:];
X.sort(key=abs)'
100000 loops, best of 3: 4.23 usec per loop

The "intrinsic" DSU done by key= is clearly superior on all scores.

The semantics are subtly different: it guarantees to never compare
anything _except_ the key (because that's typically what one wants), so,
make sure they key includes everything you may ever want compared.


Alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top