Is there a list comprehension for this?

John Machin sjmachin at
Wed Nov 22 11:28:04 CET 2006

Steven D'Aprano wrote:
> On Tue, 21 Nov 2006 21:00:02 -0800, John Machin wrote:
> > 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.
> Because rs[0-1] is just rs[-1], which fetches the LAST item of the list. I
> cunningly initialised the list to all zeroes, so adding zero to the first
> term doesn't change the result value.
> It is a variation of the sentinel technique, where you add an extra value
> to the beginning or end of a list so that you don't need to treat the
> first or last item differently. In this specific case, I think it is a
> combination of Good Idea and Fortunate Accident, but since the
> meaning of list[-1] is both deliberate and well-documented, it is
> certainly not a Filthy Trick.

Fair enough. But it does make the concerned reader go back a couple of
lines to see why it doesn't run amok. Here's my attempt at a
no-reader-backtracking solution:

def running_sum_2(dw):
    rs = dw[:1]
    for i in xrange(1, len(dw)):
        rs.append(dw[i] + rs[-1])
    return rs

Comments invited.


More information about the Python-list mailing list