HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMajor

Pythonic way to add each previous element in list

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
pythonicpreviouseachwayelementlistadd

Problem

It's a very simple question, but I wonder if there is a more pythonic way to add each previous elements in a list like this (for example with a list comprehension maybe) :

input : L = [4, 2, 1, 3]
output : new_L = [4, 6, 7, 10]


Which I've done this way :

def add_one_by_one(L):
    new_L = []
    for elt in L:
        if len(new_L)>0:
            new_L.append(new_L[-1]+elt)
        else:
            new_L.append(elt)
    return new_L

new_L = add_one_by_one(L)

Solution

In Python 3 itertools gained a new function accumulate that does what you want.
I'd recommend that you instead used this function. Or if you can't if you're in Python 2 to upgrade.
This would single handedly change your code to:

from itertools import accumulate

new_l = accumulate(l)


If you however done this as a learning exercise, then I'd instead use iterators.
I'd first change l to an iterator, via iter.
Which would allow you to use next to remove the default value.
After this I would then loop through the iterator and yield rather than new_list.append the new values.
This can allow you to get something like:

def accumulate_sum(l):
    l = iter(l)
    try:
        total = next(l)
    except StopIteration:
        return
    yield total
    for item in l:
        total += item
        yield total


Which funnily enough is almost exactly the same to how it's done in itertools.accumulate.
If you wanted to at a later date use a different function rather than addition, then you could pass that as a function, to call on each iteration.

Code Snippets

from itertools import accumulate

new_l = accumulate(l)
def accumulate_sum(l):
    l = iter(l)
    try:
        total = next(l)
    except StopIteration:
        return
    yield total
    for item in l:
        total += item
        yield total

Context

StackExchange Code Review Q#149379, answer score: 25

Revisions (0)

No revisions yet.