Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why there's a start argument in python's built-in sum function

Tags:

python

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?

like image 843
FrostNovaZzz Avatar asked Dec 28 '10 01:12

FrostNovaZzz


1 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)
like image 143
Mark Byers Avatar answered Oct 06 '22 23:10

Mark Byers