Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty tuple as 2nd parameter to sum()

Tags:

python

Why does the 2nd parameter to the sum() can be an empty tuple? Shouldn't it be a number according to https://docs.python.org/3/library/functions.html#sum?

>>> tmp=((1,2), ('a','b'))
>>> sum(tmp, ())
(1, 2, 'a', 'b')
like image 698
Haibin Liu Avatar asked Sep 05 '25 20:09

Haibin Liu


1 Answers

The 2nd parameter is the start value. This is not an index to start at, but a value to start the sum.

For example:

sum([1,2,3], 0) is the same as 0 + 1 + 2 + 3

sum([1,2,3], 6) is the same as 6 + 1 + 2 + 3

sum(((1,2), ('a','b')), ()) is the same as () + (1,2) + ('a','b')

Since start is 0 by default if you didn't specify a value for it you would get

0 + (1,2) + ('a','b')

Which gives

TypeError: unsupported operand type(s) for +: 'int' and 'tuple'

like image 65
wilkben Avatar answered Sep 08 '25 23:09

wilkben