Why is there a start argument in Python's built-in sum function?

Question:

In the sum function, the prototype is sum(iterable[,start]), which sums everything in the iterable object plus the start value. I wonder why there is a start value in here? Is there nay particular use case this value is needed?

Please don’t give any more examples how start is used. I am wondering why it exist in this function. If the prototype of sum function is only sum(iterable), and return None if iterable is empty, everything will just work. So why we need start in here?

Asked By: FrostNovaZzz

||

Answers:

If you are summing things that aren’t integers you may need to provide a start value to avoid an error.

>>> from datetime import timedelta
>>> timedeltas = [timedelta(1), timedelta(2)]

>>> sum(timedeltas)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'datetime.timedelta'

>>> sum(timedeltas, timedelta())
datetime.timedelta(3)
Answered By: Mark Byers
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.