sum() requires number, not simply __add__
ian.g.kelly at gmail.com
Thu Feb 23 16:54:22 EST 2012
On Thu, Feb 23, 2012 at 2:38 PM, Buck Golemon <buck at yelp.com> wrote:
> My proposal is still *slightly* superior in two ways:
> 1) It reduces the number of __add__ operations by one
> 2) The second argument isn't strictly necessary, if you don't mind
> that the 'null sum' will produce zero.
It produces the wrong result, though:
>>> sum([3,4], base=12)
If I'm starting with 12 and summing 3 and 4, I expect to get 19.
Ideally the second argument should be ignored only if it isn't passed
in at all, and I don't know off-hand why the built-in sum doesn't do
this. We really don't need to replace it, though. If you want a
different sum behavior, just write your own.
def sum(iterable, *args):
return reduce(operator.add, iterable, *args)
>>> sum([3,4], 12)
>>> sum(['hello', 'world'])
More information about the Python-list