Pythonic way to sum n-th list element?

Steven Taschuk staschuk at telusplanet.net
Sat Apr 19 13:17:03 EDT 2003


Quoth Guy Middleton:
> What is the most Pythonic way to sum the n-th element of a list of lists (or
> of tuples)?
  [...]
> 	>>> x = (("a", 1), ("b", 2), ("c", 3))
> 	>>> # want to sum 1+2+3 = 6

Here's a variant on the reduce solution:

    reduce(operator.add, zip(*x)[1])

zip(*x) transposes a list of lists, turning columns into rows,
whereupon you may simply index for the column you want.  In this
case this technique is surely less efficient than [y[1] for y in
x], since it creates a list for every column in x.

(I make no claim that this is the most Pythonic approach.  It's
only clear if zip(*x) is a well-known idiom, and I think it might
not be.)

-- 
Steven Taschuk                          staschuk at telusplanet.net
"Its force is immeasurable.  Even Computer cannot determine it."
                           -- _Space: 1999_ episode "Black Sun"





More information about the Python-list mailing list