空元组作为 sum() 的第二个参数

Hai*_*Liu 4 python

为什么 sum() 的第二个参数可以是空元组?它不应该是根据https://docs.python.org/3/library/functions.html#sum的数字吗?

>>> tmp=((1,2), ('a','b'))
>>> sum(tmp, ())
(1, 2, 'a', 'b')
Run Code Online (Sandbox Code Playgroud)

wil*_*ben 5

第二个参数是起始值。这不是起始索引,而是起始求和的值。

例如:

sum([1,2,3], 0)是相同的0 + 1 + 2 + 3

sum([1,2,3], 6)是相同的6 + 1 + 2 + 3

sum(((1,2), ('a','b')), ())是相同的() + (1,2) + ('a','b')

因为 start 默认是 0 如果你没有指定它的值你会得到

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

这使

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