Explain list comprehension in cumulative sum of list

Viewed 233

Python code to get the Cumulative sum of a list

def Cumulative(lists): 
    cu_list = [] 
    length = len(lists) 
    cu_list = [sum(lists[0:x:1]) for x in range(0, length+1)] 
    return cu_list[1:] 

# Driver Code 
lists = [10, 20, 30, 40, 50] 
print (Cumulative(lists)) 

Can anyone help me to expand above list comprehension ?

I have written this code

def cum_sum(m):
    result = 0
    for x in m:
        result += x
        print(result, end=", ")


cum_sum([1,2,3,10])
4 Answers

use a generator

def cum_sum(m):
    result = 0
    for x in m:
        result += x
        yield result


list(cum_sum([1,2,3,10]))

this part of your code

[sum(lists[0:x:1]) for x in range(0, length+1)]

creates a new list starting from the first element of lists up to (and excluding) the x'th element of your list (see e.g. Python List Slicing). then it takes the sum over it.

so it unnecessarily creates several lists and does unnecessary sums (it could keep the sum up to element x in memory and just add the next element - as do most solutions presented here).

you get that for free with itertools.accumulate already:

from itertools import accumulate


lists = [10, 20, 30, 40, 50]
print(list(accumulate(lists)))
# [10, 30, 60, 100, 150]
ans = []
for i in range(len(lists)):
    ans.append(sum(lists[:i+1]))

This is the expanded form of the list comprehension:

cu_list = []
for x in range(0, length+1):
    s = sum(lists[0:x:1])
    cu_list.append(s)
Related