Pythonic way to sum n-th list element?

Alex Martelli aleax at aleax.it
Fri Apr 18 17:34:24 EDT 2003


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.

Saving two lines and some bananoseconds (if that) by using reduce and
operator.add may be more to the taste of many regular readers of this
newsgroup, but I wouldn't characterize it as "most Pythonic"!-)


Alex





More information about the Python-list mailing list