This is a Python Program to find the cumulative sum of a list where the ith element is the sum of the first i+1 elements from the original list.
The program takes a list from the user and finds the cumulative sum of a list where the ith element is the sum of the first i+1 elements from the original list.
1. Declare an empty list and initialise to an empty list.
2. Consider a for loop to accept values for the list.
3. Take the number of elements in the list and store it in a variable.
4. Accept the values into the list using another for loop and insert into the list.
5. Using list comprehension and list slicing, find the cumulative sum of elements in the list.
6. Print the original list and the new list.
7. Exit.
Here is source code of the Python Program to find the cumulative sum of a list where the ith element is the sum of the first i+1 elements from the original list. The program output is also shown below.
a=[] n= int(input("Enter the number of elements in list:")) for x in range(0,n): element=int(input("Enter element" + str(x+1) + ":")) a.append(element) b=[sum(a[0:x+1]) for x in range(0,len(a))] print("The original list is: ",a) print("The new list is: ",b)
1. Use must declare a list and initialize it to an empty list.
2. Then a for loop is used to accept values for the list.
3. User must enter the number of elements in the list and store it in a variable.
4. Then the user must enter the values into the list using another for loop and insert into the list.
5. List comprehension along with list slicing is used to find cumulative sum of elements in the list
6. Then the original list and the new list is printed.
Case 1: Enter the number of elements in list:5 Enter element1:1 Enter element2:2 Enter element3:3 Enter element4:4 Enter element5:5 ('The original list is: ', [1, 2, 3, 4, 5]) ('The new list is: ', [1, 3, 6, 10, 15]) Case 2: Enter the number of elements in list:4 Enter element1:23 Enter element2:56 Enter element3:67 Enter element4:10 ('The original list is: ', [23, 56, 67, 10]) ('The new list is: ', [23, 79, 146, 156])
Sanfoundry Global Education & Learning Series – Python Programs.
To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.
- Apply for Python Internship
- Check Python Books
- Apply for Programming Internship
- Check Information Technology Books
- Practice Programming MCQs