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

MRAB python at mrabarnett.plus.com
Sat Dec 5 17:43:15 CET 2009


Ram Rachum wrote:
> I noticed that `sum` tries to add zero to your iterable. Why? Why not
> just skip adding any start value if none is specified?
> 
> This current behavior is preventing me from using `sum` to add up a 
> bunch of non-number objects.
> 
Sometimes you might find that the list you're summing is empty. Because
'sum' is most often used with numbers, the default sum of a list is 0.
If you want to sum a list of non-numbers, provide a suitable start
value. For example, to sum a list of lists a suitable start value is []:

>>> sum([[0, 1], [2, 3]], [])
[0, 1, 2, 3]

I agree that it would be nice if the start value could just be omitted,
but then what should 'sum' return if the list is empty?

If sum([1, 2]) returned 3, then I'd want sum([]) to return 0.

If sum([[1], [2]]) returned [1, 2], then I'd want sum([]) to return [].

Unfortunately, I can't have it both ways.



More information about the Python-ideas mailing list