Python 3: apply an operator over an iterable
Question: `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`.


Answer: Try looking into the python reduce function:
<http://docs.python.org/library/functions.html#reduce>

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.

