4

In Python, if I wanted to use explicit functional-style programming to sum up a list, I could do

>>> import operator
>>> reduce(operator.add, [3, -1, 2])
4

Mathematica, being closer to a pure functional language than Python, calls it Fold instead of reduce, but the outcome is the same.

In[1]:= Fold[Plus, {3, -1, 2}]
Out[1]= 4

So now, in Mathematica, if I wanted to get the result of the "fold" at every step during the iteration, I could use the function FoldList.

In[2]:= FoldList[Plus, {3, -1, 2}]
Out[2]= {3, 2, 4}

How do I get such a list (or preferably an iterator) in Python? In general, does this functional operation have a name?

sffc
  • 6,186
  • 3
  • 44
  • 68
  • 1
    The subroutine is usually called `scan`, the mathematical operation is called *prefix sum*. – Jörg W Mittag Oct 02 '15 at 01:19
  • @gnat Rather than downvoting my post, if you're a mod, can you just move the question to the right board? My question is fine and my answer is correct. I always seem to pick the wrong StackExchange. – sffc Oct 02 '15 at 05:06
  • A couple of years ago, I tried moving a question from I think Stack Overflow to Server Fault by re-posting it, but the mods told me that I wasn't supposed to do that and that I should have asked them to move the question instead. – sffc Oct 02 '15 at 08:58

1 Answers1

5

I found the right function: in Python, it's called accumulate.

>>> from itertools import accumulate
>>> list(accumulate([3, -1, 2], operator.add))
[3, 2, 4]

It appears to only be available in Python 3. But everyone has upgraded by now, right? :)

sffc
  • 6,186
  • 3
  • 44
  • 68
  • Simple `list(accumulate([3, -1, 2]))` is sufficient. `itertools.accumulate` is new in Python 3.2. – vaultah Oct 03 '15 at 14:18
  • I came to this question (based on its general title) with a more general function instead of `operator.add` (say `lambda x, y: 2*x + 0.1*y`). For such functions the solutions works as well. If your question exceeded the sum, you could consider editing it and emphasising the general purpose. – Qaswed Oct 23 '19 at 09:29