[Python-ideas] Why does `sum` use a default for the `start` parameter?

Raymond Hettinger python at rcn.com
Sat Dec 5 20:31:14 CET 2009

[Ram Rachum]
>I noticed that `sum` tries to add zero to your iterable. Why? Why not just skip 
> adding any start value if none is specified?

Once the API has been released, it is difficult to change without breaking code.

> This current behavior is preventing me from using `sum` to add up a bunch of non-
> number objects.

You have plenty of options:
* use sum() as designed and supply your own Zero object as a start (see below)
* use reduce(operator.add, s)
* write a simple for-loop to do summing

It's not like summing is a hard task. There's nothing in you situation that
would warrant changing the behavior of a published API where sum(s)
is defined even when s is of length zero or one.



>>> class Zero:
...     'universal zero for addition'
...     def __add__(self, other):
...         return other
...     def __radd__(self, other):
...         return other
>>> Zero() + 'xyz'
>>> sum(['xyz pdq'], Zero())
'xyz pdq'

More information about the Python-ideas mailing list