[Tutor] .sort(key = ???)

John Fouhy john at fouhy.net
Fri Nov 17 00:10:58 CET 2006


Incidentally, I was wondering what the value of using
operator.itemgetter is.  So I ran some tests.

Morpork:~/offlode repton$ python -m timeit -s 'import math' -s 'a =
[(i, math.sin(i)) for i in range(10000)]' -s 'f = lambda e: e[1]'
'sorted(a, key=f)'
10 loops, best of 3: 22.4 msec per loop

Morpork:~/offlode repton$ python -m timeit -s 'import math' -s 'import
operator' -s 'a = [(i, math.sin(i)) for i in range(10000)]' -s 'f =
operator.itemgetter(1)' 'sorted(a, key=f)'
100 loops, best of 3: 18.7 msec per loop

So, slight win for operator.itemgetter.  I'm not sure exactly how much
of a win, since there's all those calls to cmp in the sort operation
as well..

Incidentally, here's what happens if you define your own cmp function
instead (the way you had to in python <= 2.3):

Morpork:~/offlode repton$ python -m timeit -s 'import math' -s 'import
operator' -s 'a = [(i, math.sin(i)) for i in range(10000)]' -s 'f =
lambda x, y: cmp(x[1], y[1])' 'sorted(a, cmp=f)'
10 loops, best of 3: 163 msec per loop

And decorate-sort-undecorate:

Morpork:~/offlode repton$ python -m timeit -s 'import math' -s 'import
operator' -s 'a = [(i, math.sin(i)) for i in range(10000)]' 'b =
[(e[1], e) for e in a]' 'b.sort()' '[e[1] for e in b]'
10 loops, best of 3: 33.9 msec per loop

Ho hum..

-- 
John.


More information about the Tutor mailing list