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

Georg Brandl g.brandl at gmx.net
Sat Dec 5 18:35:07 CET 2009

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.


Thus spake the Lord: Thou shalt indent with four spaces. No more, no less.
Four shall be the number of spaces thou shalt indent, and the number of thy
indenting shall be four. Eight shalt thou not indent, nor either indent thou
two, excepting that thou then proceed to four. Tabs are right out.

More information about the Python-ideas mailing list