Pythonic way to sum n-th list element?

Alex Martelli aleax at
Sat Apr 19 10:13:25 CEST 2003

David Eppstein wrote:

> In article <C8_na.646$dP1.2863 at>,
>  "Tim Gahnström /Bladerman" <tim at> wrote:
>> > What's wrong with:
>> >
>> > t = 0
>> > for y in x:
>> >      t += y[1]
>> >
>> > The extra variable?  The number of lines?
>> I am really curious about that to, I would most definitley say that this
>> is the most pythonic way. It is simple and easily readabel by anyone and
>> I am sure it is just as fast any of the other way.
> If you want the sum of a list of items, you should write it in a way
> that looks like "the sum of a list of items", not in a way that looks

"The sum" is so frequently needed that I wouldn't mind at all if
Python singled it out as a built-in.  But "reduce(operator.add, ..."
just isn't a great way to express it, in my opinion (and yet as an
old APL'er, and FP-liker, I _should_ like it -- but I don't).

> like "loop over these items, maintain another variable t, perform a
> sequence of additions".  Why do we have high level languages if not to
> express our intentions at a higher level and let the language worry
> about what low-level operations are needed to implement it?

We use VHLL's to enhance our programming productivity.  There's no
*mandate* that each idiom MUST be very abstract and require higher
maths; on the contrary, Python thrives on simplicity and directness.

"sum([y[1] for y in x])" would be very simple and direct, IMHO; the
"same" thing expressed with "reduce(operator.add,[y[1] for y in x])"
may only feel "simple and direct" to PhD's in maths -- it feels
_abstruse_ to most people, in my opinion.

Python isn't about being abstruse.


More information about the Python-list mailing list