sum(iterable) is effectively:
def sum(iterable):
s = 0
for x in iterable:
s = s.__add__(x)
return s
Does Python have a built-in function that accomplishes this without setting the initial value?
# add is interchangeable with sub, mul, etc.
def chain_add(iterable):
iterator = iter(iterable)
s = next(iterator)
while True:
try:
s = s.__add__(next(iterator))
except StopIteration:
return s
The problem I have with sum is that it does not work for other types that support the + operator, e.g. Counter.
Try looking into the python
reduce()function: You pass in a function, an iterable, and an optional initializer and it would apply the function cumulatively to all the values.For example:
You can change the function based on your iterable, so it’s very customizable.