Python – Adds the previous element to the current element in the list and then assigns to a variable – Python 3.5.2

Adds the previous element to the current element in the list and then assigns to a variable – Python 3.5.2… here is a solution to the problem.

Adds the previous element to the current element in the list and then assigns to a variable – Python 3.5.2

First post, excited! Ok, here comes the question: how to add the previous element to the current element, and then create a new list based on those values to add them to the matplotlib graph? Here is my code example:


example_list = [20, 5, 5, -10]

print(example_list) '''first output should be'''
[20, 5, 5, -10]

value1 = (example_list[0])
value2 = (example_list[0] + example_list[1])
value3 = (example_list[0] + example_list[1] + example_list[2])
value4 = (example_list[0] + example_list[1] + example_list[2] + example_list[3])

”I think you can understand what I’m trying to say””

Delete the example list [:]

example_list.append(value1)
example_list.append(value2)
example_list.append(value3)
example_list.append(value4)

print(example_list)
'''output should be:'''

[20, 25, 30, 20]

”’This works well for hardcoding it, but I expect this to happen on hundreds of elements. (When people add to the list from my “simple_finance_app” Python script) ”’Thanks for the help! (P.S. I already have the matplotlib code, so no need to add it, however, I can help others reading this question/answer)

Solution

You can use itertools.accumulate Method:

<b>from itertools import accumulate
from operator import add</b>

result = list(<b>accumulate(</b>example_list<b>,add)</b>).

This produces:

>>> list(accumulate(example_list,add))
[20, 25, 30, 20]

If the function (here operator.add) runs in O(n), then accumulate will run in O( n) and your hardcoded solution runs in O(n2).

Basically the accumulate(iterable[,func]) function takes an iterable [x1,x2,...,xn] and a function as input f, and each iteration calls f on the accumulator and new elements. In the first step, it emits the first element, and then the accumulator becomes that element. So it basically generates [x1,f(x1,x2),f(f(x1,x2),x3),...]. But f (x1.x2) is not calculated every time. Therefore it is semantically equivalent to:

def accumulate(iterable,func): # semantical equivalent of itertools.accumulate
    iterer = iter(iterable)
    try:
        accum = next(iterer)
        while True:
            yield accum
            accum = func(accum,next(iterer))
    except StopIteration:
        pass

But it may be less error-prone and more efficient.

Related Problems and Solutions