Pythonic way to sum n-th list element?

Guy Middleton guy at obstruction-no-spam.com
Fri Apr 18 17:49:43 EDT 2003


In article <Ab_na.34355$LB6.777939 at news1.tin.it>,
Alex Martelli  <aleax at aleax.it> wrote:
> Guy Middleton wrote:
> 
> > What is the most Pythonic way to sum the n-th element of a list of lists
> > (or of tuples)?
> 
> _most Pythonic_ is probably:
> 
> total = 0
> for sublist in listoflists:
>     total = total + sublist[n]
> 
> I think that's what Guido would do if asked -- it's simple, it's entirely
> obvious, it's totally maintainable and clear.

It turns out this way is almost twice as fast as the list comprehension:

listoflists = (
    (1, 1),
    (2, 2),
    ...
    (100, 100)
    )

print time.clock()
for i in xrange(10000):
    total1 = 0
    for sublist in listoflists:
	total1 = total1 + sublist[1]
print time.clock()
for i in xrange(10000):
    total2 = reduce(operator.add, [x[1] for x in listoflists])
print time.clock()
print total1, total2


$ ./tt.py 
0.046875
2.5703125
7.234375
5050 5050
$




More information about the Python-list mailing list