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
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
running_totalstarts at 0 and has each number added to it in turn.- After each addition, the current total is appended to
cumulative. - 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.
{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()
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
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.
Related programs
- Find the Sum of Elements in a List
- Multiply All Numbers in a List
- Find the Sum of a Series
- Print the Fibonacci Series
- Find the Largest and Smallest Number in a List
- Swap Elements at Even and Odd Positions in a List
- Find the Second Largest Number in a List
- Remove Duplicates from a List
- a Menu-Driven List
- Reverse a List
All Python programs · CBSE class 12 practical file · Python exercises