Pythonic way to sum n-th list element?
Alex Martelli
aleax at aleax.it
Sat Apr 19 15:31:52 EDT 2003
Steven Taschuk wrote:
> Quoth Alex Martelli:
> [...]
>> "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.
>
> What if operator.add were changed to take any number of arguments?
> Then you could write
> operator.add(*[y[1] for y in x])
> Clear? Abstruse?
That would be quite acceptable. After all, it would then take
nothing more than a simple:
from operator import add as sum
to get my favourite syntax sugar for the operation:-).
What would you have operator.add return when called with no
arguments, though? Either 0 or 0.0 or '' or ... have problems.
I think it should be callable with ONE OR MORE arguments,
not with ANY number.
> Btw, I don't know about most people, but I don't have a PhD in
> math, and reduce(operator.add, L) seems simple and clear to me.
> (I do agree that there is a point beyond which abstraction brings
> diminishing returns; but reduce is well inside that limit, imho.)
Guess we'll have to agree to disagree. I came to Python with
lots of experience disposing me to favour reduce (no PhD either,
I'm an engineer -- but, lots of APL, functional languages, etc).
Four years later, having coded a lot of Python, taught it widely,
written a lot about it, and so on, I've changed my mind: I now
think that reduce is more trouble than it's worth and Python
would be better off without it, if it was being designed from
scratch today -- it would not substantially reduce (:-) Python's
power and WOULD substantially ease the teaching/&c task. That's
not a strong-enough argument to REMOVE a builtin, of course, and
thus that's definitely NOT what I'm arguing for. But I do suggest
avoiding reduce in most cases -- that's all.
Alex
More information about the Python-list
mailing list