Get sum or any scalar from iterable
Built-In function reduce()
reduce(function, iterable, start_value)
reduce(lambda x, y: x+y, range(0,10))
#45
The function here has two parameters. The calling flow is as below:
call: function(element[0], element[1]), save to temporary value tmp
call: function(tmp, element[2]), save to tmp
call: function(tmp, element[3]), save to tmp
Until loop completion.
The call-flow as described by official document is:
def reduce(function, iterable, initializer=None):
it = iter(iterable)
if initializer is None:
try:
initializer = next(it)
except StopIteration:
raise TypeError('reduce() of empty sequence with no initial value')
accum_value = initializer
for x in it:
accum_value = function(accum_value, x)
return accum_value
Therefore, the loop times is length of iterable minus 1.
However, if \_add\_(_, __) is visible to type, sum(list) is a quick way to return summary of all numbers.