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:
import functools
def f(x,y):
return x+y
print functools.reduce(f, [1, 2, 3, 4]) # prints 10
print functools.reduce(f, [1, 2, 3, 4], 10) # prints 20, because it initializes at 10, not 0.
You can change the function based on your iterable, so it's very customizable.
In the case of addition:
import operator
reduce(operator.add, iterable)
This will work on iterables that can't be added together using sum. Similarly, you could perform multiplication using
reduce(operator.mul, iterable)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With