6

Given the following list:

a=[1,2,3]

I'd like to generate a new list where each number is the sum of it and the values before it, like this:

result = [1,3,6]

Logic:

1 has no preceding value, so it stays the same.

3 is from the first value (1) added to the value of the second number in the list (2)

6 is from the sum of 1 and 2 from the first two elements, plus the third value of 3.

Thanks in advance!

SudoKid
  • 439
  • 4
  • 14
Dance Party
  • 3,459
  • 10
  • 42
  • 67

7 Answers7

17

Python 3 has itertools.accumulate for exactly this purpose:

>>> from itertools import accumulate
>>> a=[1,2,3]
>>> list(accumulate(a))
[1, 3, 6]
personal_cloud
  • 3,943
  • 3
  • 28
  • 38
niemmi
  • 17,113
  • 7
  • 35
  • 42
8

If you'd like a numpy solution

from numpy import cumsum
result = list(cumsum(a))
gsmafra
  • 2,434
  • 18
  • 26
3

How about an ordinary loop?

a = [1,2,3]
result = []
s = 0
for item in a:
    s += item
    result.append(s)

print(result)
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
2

Python has a function for this.

import itertools

result = list(itertools.accumlate([1, 2, 3]))

Python itertools solve some problems really well you should take some time and read over them.

https://docs.python.org/3/library/itertools.html

SudoKid
  • 439
  • 4
  • 14
2

Avinash Raj's code doesn't work correctly.

a = [1,2,3]
b = [sum(a[:(i+1)]) for i, j in enumerate(a)]
print(b)

Edited based on @Avinash Raj

Shobeir
  • 127
  • 7
  • yep, much simpler one `[sum(a[:i+1]) for i,j in enumerate(a)]` – Avinash Raj Dec 30 '16 at 05:47
  • While this has the advantage of being declarative and thus nicely readable, it notably has a worse time complexity (O(n^2)) compared to the simple iterative solution with a mutable cumulation variable (which has O(n)). – Mario Boley Aug 15 '20 at 21:58
2

try this..

def running_sum(a):
  tot = 0
  for item in a:
    tot += item
    yield tot

a = [1,2,3,4]
print list(running_sum(a))
Shivkumar kondi
  • 6,458
  • 9
  • 31
  • 58
1

There are about a hundred different ways to do this kind of cumulative sum. Depending on what you actually want to use the result for, a less obvious or less general-purpose solution might be more time- or memory-efficient—although the simple solution below is O(1) in terms of memory and O(N) in time.

The most straightforward procedural approach in virtually every imperative programming language goes something like this:

csum=0
result=[]
for val in a:
    csum += val
    result.append(csum)

The Python standard library also includes a function to do just this: itertools.accumulate.

import itertools
result = list(itertools.accumulate(a))
Dan Lenski
  • 76,929
  • 13
  • 76
  • 124