0

I have a Python array, and I want to write a single expression that returns an array with sum of all previous numbers. For example we have:

arr1 = [1,2,3,4]

And my function should return :

[1, 3, 6, 10]

I know that it's possible to make it with simple loop or even recursivly, but is it possible to make in one line? Something like:

def converter(arr):
    arr1 = [x + y for x,y in arr ]
    return arr1
randomir
  • 17,989
  • 1
  • 40
  • 55

1 Answers1

1

Since Python 3.2, you can use itertools.accumulate:

>>> from itertools import accumulate
>>> arr = [1,2,3,4]
>>> list(accumulate(arr))
[1, 3, 6, 10]
randomir
  • 17,989
  • 1
  • 40
  • 55