2

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.)

Dubslow
  • 553
  • 2
  • 6
  • 15
  • What's the input, and what's the expected output. – Aesthete Dec 08 '12 at 00:50
  • Well that would depend on what the user wants. `accumulate([5,3,1], lambda x, y: x-y)` would return 5-3-1 = 1; `accumulate([1,3,5,4], lambda x, y: x*y)` would return 1*3*5*4 = 20. (In my particular use case, I have a list of tuples, and thus my function wouldn't be a lambda, but a proper named function, but that doesn't matter.) – Dubslow Dec 08 '12 at 00:53
  • 1
    @Dubslow: do you mean: [`functools.reduce`](http://docs.python.org/3/library/functools.html#functools.reduce)? For example, see [Useful code which uses reduce() in python](http://stackoverflow.com/questions/15995/useful-code-which-uses-reduce-in-python) – jfs Dec 08 '12 at 01:09
  • @J.F.Sebastian Yes, that's exactly what I was looking for. I've never heard of functools, thanks. – Dubslow Dec 08 '12 at 01:22

1 Answers1

3

The usual name for that function is fold or reduce, and it's actually built into Python 2 under the latter name:

>>> reduce(lambda x,y: x*y, [1,3,5,4])
60

In Python 3 you have to import it from the functools module.

Mark Reed
  • 91,912
  • 16
  • 138
  • 175
  • 1
    In Python 3 `reduce` is no longer available directly, but as @J.F.Sebastian commented, you can still find it in the `functools` module. – Blckknght Dec 08 '12 at 01:18
  • Why would they make it no longer available? But yes, thanks to you three for clearing me up. – Dubslow Dec 08 '12 at 01:22
  • Reportedly because Guido doesn't like higher-order functional programming. List comprehensions solve many of the same sorts of problems in a different way. – Mark Reed Dec 08 '12 at 01:26