FrostNovaZzz
FrostNovaZzz

Reputation: 842

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

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?

Upvotes: 9

Views: 3761

Answers (1)

Mark Byers
Mark Byers

Reputation: 838696

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)

Upvotes: 16

Related Questions