Pythonic way to sum n-th list element?

Fernando Perez fperez528 at yahoo.com
Fri Apr 18 17:40:07 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)?
> 
> The obvious (to me) way is to use reduce, a list comprehension, and a
> lambda:
> 
> $ python
> Python 2.2.1 (#1, Jul  4 2002, 15:23:46)
> [GCC 2.95.3 20010315 (release) [FreeBSD]] on freebsd4
> Type "help", "copyright", "credits" or "license" for more information.
> >>> x = (("a", 1), ("b", 2), ("c", 3))
> >>> # want to sum 1+2+3 = 6
> ...
> >>> reduce(lambda a, b: a+b, [y[1] for y in x])
> 6

People often don't know (or forget) that Numeric is not only useful for
numerical work, but also because it has the cleanest possible syntax for
handling multi-dimensional arrays (even heterogeneous ones):

In [16]: x=array((("a", 1), ("b", 2), ("c", 3)),typecode='O')

In [17]: sum(x[:,1])
Out[17]: 6


Best,

f.




More information about the Python-list mailing list