简体   繁体   中英

Why does `sum` need `start` parameter?

For example, to calculate sum of timedelta list, we need to write below:

sum(l, timedelta())

(l is list of instances of timedelta )

But we can calculate that without the start variable, like

l[0] + l[1] + l[2] + ...

Why the builtin sum function needs start value?

EDIT

If the sum function defined like

def sum2(l):
     return l[0] + (sum2(l[1:]) if len(l) > 2 else l[1])

and got sum2([[1, 2], [2, 4], [3, 5]]) -> [1, 2, 2, 4, 3, 5] work well without start value.

I don't understand why sum don't work like this.

sum is roughly equivalent to the following function:

def sum(iter, start=0):
   for element in iter:
       start = start + iter
   return start

This is the typical use case:

sum([1, 2, 3]) -> 6

But if you want to use it with an object which doesn't define integer addition you need to define the starting value. For example if you want to flatten a nested list.

sum([[1, 2], [2, 4], [3, 5]], []) -> [1, 2, 2, 4, 3, 5]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM