In some code I'm writing, I'd like a function similar to the built in sum() function, except with my own custom two-argument function as opposed to addition. It's easy to write such a function, but I'm wondering if there's one in the standard library somewhere? I took a look through the itertools doc, but didn't find anything. It would also be similar to itertools.accumulate(mylist)[-1]
, except with functions other than sums.
My own code for such a function:
def accumulate(iterable, func):
it = iter(iterable)
out = func(next(it), next(it))
for i in it:
out = func(out, i) # "out += i"
return out
So sum(mylist)
would be equivalent to accumulate(mylist, lambda x, y: x+y)
. In my use case of course, I have a different function I'd like to use (it is more complicated than a simple arithmetic operation.)
It seems like this would be a fairly common thing, which is why I'm surprised half an hour of searching didn't find anything like this. So: If and where does such a function exist in the standard library? (I'm using my own code above for now.)