Is there a list comprehension for this?

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Wed Nov 22 05:18:00 EST 2006


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. 


-- 
Steven.




More information about the Python-list mailing list