How to Get the Cumulative Sum of a List in Python


In this example, we will learn how to find the cumulative sum of the list, where the ith element is the sum of the first number until the ith number in the original list.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

def userList():
    n = int(input("Please input he number of elements: "))
    a = []
    for i in range(n):
        j = int(input("Please input the " + str(i + 1) + "th element: "))
        a.append(j)
    return a

a = userList()
print("The original list: ", a)
b = [sum(a[0:x+1]) for x in range(len(a))]
print("The new list: ", b)

Output:

Please input he number of elements: 5
Please input the 1th element: 10
Please input the 2th element: 12
Please input the 3th element: 14
Please input the 4th element: 16
Please input the 5th element: 18
The original list: [10, 12, 14, 16, 18]
The new list: [10, 22, 36, 52, 70]
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement