Using Python 2
1 Using Python 2
1.Ninja way:
1.1 Ninja way
Is fun and good for learning python, but don't go for it in production code
from operator import iadd l = [4,2,1,3] reduce(lambda result, x: iadd(result, [result[-1] + x]), l, [0])[1:] 2.Explicit way
1.2 Explicit way
I will just copy @Grapier solution for this because I would do the same:
def add_one_by_one_gen(l): cumsum = 0 for elt in l: cumsum += elt yield cumsum Using Python 3
2 Using Python 3
from itertools import accumulate accumulate(l)