How to calculate sum using list comprehension

12,405

Solution 1

List comprehensions are for mapping or filtering of lists. They cannot have an internal state, which is what you would need to do this efficiently.

However in Python 3 there is itertools.accumulate for that:

import itertools

print(list(itertools.accumulate([1, 4, 9, 16])))  # [1,5,14,30]

Solution 2

You can do it like this, by combining slicing and a list comprehension, but it is ungainly to do a cumulative sum efficiently.

comp=[1,4,9,16] 
[sum(comp[:idx+1]) for idx in range(len(comp))]

I would not recommend using this, it recalculates the sum n times!


A proper way to cumsum can be done like this:

def cumsum(seq):
    cumulative = [seq[0]]
    for elt in seq[1:]:
        cumulative.append(cumulative[-1] + elt)
    return cumulative

itertools.accumulate is another way that @NielsWerner demonstrated.


Further efficiency can be found with the numpy library, and the cumsum function of this library.

Solution 3

the walrus operator can help to solve this task:

lst = [1,4,9,16] # expected result: [1,5,14,30] 
buf = 0
res = [buf := buf + num for num in lst]
print(res)

[Note : walrus operator is introduced in python 3.8]

Share:
12,405

Related videos on Youtube

bit
Author by

bit

Updated on May 25, 2022

Comments

  • bit
    bit almost 2 years

    How do I get the cumulative sum of this list using list comprehension:

    list_comp=[1,4,9,16] 
    

    Here's what I tried but it prints the double of each item in the list

    print([x+x for x in list_comp])
    

    I expect the results to be: list_comp=[1,5,14,30] But I'm getting this:

    >> [2, 8, 18, 32]
    
  • Manjunath
    Manjunath over 6 years
    I think accumulate is introduced in Python 3?
  • Nils Werner
    Nils Werner over 6 years
    Yes, I will add that. But the question targets Python 3 anyways.
  • Pratik Charwad
    Pratik Charwad almost 3 years
    walrus operator is introduced in python 3.8