Editor

Python Program to Find the Cumulative Sum of a List

Beginner · Lists

The cumulative sum, also called the running total, replaces each element with the sum of that element and all the elements before it. For [10, 20, 30] it is [10, 30, 60]. This program keeps a running total and prints how it grows.

Program

cumulative_sum.py
numbers = [10, 20, 30, 40, 50] # or: numbers = [int(x) for x in input("Enter numbers: ").split()]
running_total = 0
cumulative = []
for num in numbers:
running_total += num
cumulative.append(running_total)
print(f"Add {num:>2} -> running total {running_total}")
print("List:", numbers)
print("Cumulative sum:", cumulative)
Output
Add 10 -> running total 10
Add 20 -> running total 30
Add 30 -> running total 60
Add 40 -> running total 100
Add 50 -> running total 150
List: [10, 20, 30, 40, 50]
Cumulative sum: [10, 30, 60, 100, 150]

How it works

  1. running_total starts at 0 and has each number added to it in turn.
  2. After each addition, the current total is appended to cumulative.
  3. So the second entry is 10 + 20 = 30, the third is 10 + 20 + 30 = 60, and the last one equals the sum of the whole list.
  4. {num:>2} pads the number to two characters on the right, which keeps the printed steps lined up.

Other ways to write it

Using itertools.accumulate()

Using itertools.accumulate()
from itertools import accumulate
import operator
numbers = [10, 20, 30, 40, 50]
print("Cumulative sum:", list(accumulate(numbers)))
print("Running product:", list(accumulate([1, 2, 3, 4, 5], operator.mul)))
print("Running maximum:", list(accumulate([3, 1, 4, 1, 5, 9, 2], max)))
Output
Cumulative sum: [10, 30, 60, 100, 150]
Running product: [1, 2, 6, 24, 120]
Running maximum: [3, 3, 4, 4, 5, 9, 9]

accumulate() builds the running total for you, and with a second argument it can keep a running product or a running maximum instead.

Using sum() of slices

Using sum() of slices
numbers = [10, 20, 30, 40, 50]
cumulative = [sum(numbers[:i + 1]) for i in range(len(numbers))]
print("Cumulative sum:", cumulative)
Output
Cumulative sum: [10, 30, 60, 100, 150]

numbers[:i + 1] is every element up to index i. It is short, but each entry adds the numbers up again from the start, so it is slower on long lists.

Try it yourself

Use the daily rainfall list [5, 0, 12, 3, 8] and find on which day the total first passes 15.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises