# Is there a list comprehension for this?

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Wed Nov 22 05:33:02 CET 2006

```On Tue, 21 Nov 2006 13:19:04 -0800, liam_herron wrote:

>
> Given:
> dw = [ 1, -1.1, +1.2 ]
>
> Suppose I want to create a list 'w' that is defined as
>
> w[0] = dw[0],
> w[1] = w[0] + dw[1],
> w[2] = w[1] + dw[2]
>
> Is there a list comprehension or map expression to do it in one or 2
> lines.

This isn't a list comp and it doesn't need map, but if you
absolutely have to have a one-liner:

w = [dw[0], dw[0] + dw[1], dw[0] + dw[1] + dw[2]]

Obviously that doesn't scale at all to larger lists, but it gives you a
better idea: replace the manual additions with sum().

w = [sum(dw[0:i]) for i in range(1, len(dw))]

but if your dw list is huge, you're spending a lot of time slicing
dw and adding up the same numbers over and over again. (This doesn't
matter if dw is small, but could become expensive if dw is huge.)

Which leads to the next version:

def running_sum(dw):
"""Return a list of the running sums of sequence dw"""
rs = [0]*len(dw)
for i in range(len(dw)):
rs[i] = dw[i] + rs[i-1]
return rs

It isn't a one-liner, but it is clear, the name is self-documenting, it
has a doc-string, you don't have to copy-and-paste code every time you
want to use it, and now that you've defined it once, you can use it as a
one-liner as many times as you like.

>>> running_sum(range(5)):
[0, 1, 3, 6, 10]

--
Steven D'Aprano

```