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

MRAB python at mrabarnett.plus.com
Sat Dec 5 19:12:31 CET 2009

Georg Brandl wrote:
> Ram Rachum schrieb:
>>> 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?
>> I see the problem. I think a good solution would be to tell the
>> user, "If you want `sum` to be able to handle a non-empty list, you
>> must supply `start`." Users that want to add up a (possibly empty)
>> sequence of numbers will have to specify `start`.
>> If start is supplied, it will work like it does now. If start isn't
>> supplied, it will add up all the elements without adding any
>> `start` to them.
>> What do you think?
> (sorry, pressed wrong key)
> There is a choice between these two variants:
> a) require start for non-numerical sequences
 > b) require start for possibly empty sequences
> I don't have a preference for either, so for compatibility's sake I
> would vote to keep the current one, which is a).  It also stands to
> reason that buggy usage in case b) is harder to detect, since the
> common case will not uncover the bug (the sequence being nonempty),
> while for case a) it does.
True, providing start will ensure that the result is of the correct
class, instead of it sometimes being an int, causing a TypeError later

More information about the Python-ideas mailing list