Is there a list comprehension for this?

John Machin sjmachin at lexicon.net
Wed Nov 22 00:00:02 EST 2006


Steven D'Aprano wrote:

[snip]

> 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]

Please explain to the newbies why there is no exception raised when
rs[i-1] is executed for i == 0, and state whether you consider this is
a Good Idea or a Filthy Trick or a Fortunate Accident.

>     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]




More information about the Python-list mailing list