4 ms·
> ...faster and often clearer than lambdas. $ python -m timeit 'import string;from operator import itemgetter;[itemgetter('slice') for x in string.letters]
by atdt 14y ago
> ...faster and often clearer than lambdas.
$ python -m timeit 'import string;from operator import itemgetter;[itemgetter('slice') for x in string.letters]'
100000 loops, best of 3: 14.2 usec per loop
$ python -m timeit 'import string;from operator import itemgetter;[lambda x: x.slice for x in string.letters]'
100000 loops, best of 3: 10.4 usec per loop
> Also: namedtuple is great instead of "using classes as attribute containers".
Er, OK. Just don't look at the implementation[1]. Cannot be unseen.
[1]: http://hg.python.org/cpython/file/2.7/Lib/collections.py#l233 http://hg.python.org/cpython/file/2.7/Lib/collections.py#l23...
- bvdbijl 14y agoMy eyes... So a named tuple is just a class, nothing special about it really
- andreasvc 14y agoYou're measuring the wrong thing. itemgetter() is supposed to be called just once and it's the returned function that is used in the loop/map. It should be: python -m timeit 'import string;from operator import itemgetter; getter=itemgetter('slice'); [getter(x) for x in string.letters]'
- benhoyt 14y agoTrue. But you should also put the setup in a -s option, because you're not timing the imports. And you don't really need the loop, because timeit does a bunch of loops for you: >python -m timeit -s "from operator import itemgetter; elem0 = itemgetter(0)" "elem0('s')" 10000000 loops, best of 3: 0.095 usec per loop >python -m timeit -s "from operator import itemgetter; elem0 = lambda x: x[0]" "elem0('s')" 10000000 loops, best of 3: 0.138 usec per loop