Python generator that can do cumulative sum of the previous elements

Viewed 35

I am working with Python3 and trying to create a oneliner that creates a generator that can return the cumulative sum of members of a list.

For example, given the list [1, 2, 3, 4], the generator expression should return 1, 3, 6, 10 in each call to next.

I know how to do this with several lines of code. I would like to find a way to do it as a Python oneliner. The problem I find is how to access the previous values.

2 Answers

You can use:

x = [1, 2, 3, 4]

The following one-liner will return the desired result:

[i for i in itertools.accumulate(x)]

This will return:

[1, 3, 6, 10]

You can do

[sum(lst[:n+1]) for n in range(len(lst))]

but this in inefficient, since every sum is recomputed from scratch. An efficient approach would require an accumulator variable, which is not possible in a comprehension.

Related