Pythonic way to sum n-th list element?

Anton Vredegoor anton at vredegoor.doge.nl
Sat Apr 19 15:03:38 CEST 2003


Alex Martelli <aleax at aleax.it> wrote:

>[alex at lancelot python2.3]$ python -O timeit.py -s"lst=[('a',1), ('b',2), 
>('c',3)]*100" -s'import operator' 'x=0' 'for y in lst: x+=y[1]'
>10000 loops, best of 3: 103 usec per loop
>
>Using lists 10 or 100 times as long seems to show O(N) behavior for
>each case, as could be expected.  So, the simplest (and I would agree
>thereby most Pythonic) approach is over twice as fast as the fancy ones
>(measurements on 2.2.2 seem to show similar results, all approaches
>being about 20% slower than in 2.3, uniformly).

Unpacking the tuple early seems to be 9% faster, if Knuth allows it.

Anton

Anton Vredegoor at hyperspace ~
$ python -O timeit.py -s"lst=[('a',1), ('b',2), 
('c',3)]*100" -s'import operator' 'x=0' 'for y in lst: x+=y[1]'
10000 loops, best of 3: 125 usec per loop

Anton Vredegoor at hyperspace ~
$ python -O timeit.py -s"lst=[('a',1), ('b',2), 
('c',3)]*100" -s'import operator' 'x=0' 'for i,j in lst: x+=j'
10000 loops, best of 3: 115 usec per loop






More information about the Python-list mailing list