Write a Python Program to find Sum of Elements in a List with a practical example.
Python Program to find Sum of Elements in a List
This python program allows user to enter the length of a List. Next, we used Python For Loop to add numbers to the list.
TIP: Python sum function returns the sum of all the elements in a List
# Python Program to find Sum of all Elements in a List NumList = [] Number = int(input("Please enter the Total Number of List Elements : ")) for i in range(1, Number + 1): value = int(input("Please enter the Value of %d Element : " %i)) NumList.append(value) total = sum(NumList) print("\n The Sum of All Element in this List is : ", total)
Program to find Sum of Elements in a List without using sum
In this program, we are using For Loop to iterate each element in this list. Inside the loop, we are adding those elements to the total variable.
# Python Program to find Sum of all Elements in a List NumList = [] total = 0 Number = int(input("Please enter the Total Number of List Elements : ")) for i in range(1, Number + 1): value = int(input("Please enter the Value of %d Element : " %i)) NumList.append(value) for j in range(Number): total = total + NumList[j] print("\n The Sum of All Element in this List is : ", total)
Python Program to Calculate Sum of Elements in a List using While loop
This Python program to return the sum of list items is the same as the above. We just replaced the For Loop with While loop.
# Python Program to find Sum of all Elements in a List NumList = [] total = 0 j = 0 Number = int(input("Please enter the Total Number of List Elements : ")) for i in range(1, Number + 1): value = int(input("Please enter the Value of %d Element : " %i)) NumList.append(value) while(j < Number): total = total + NumList[j] j = j + 1 print("\n The Sum of All Element in this List is : ", total)
Python Program to Calculate Sum of all Elements in a List using Functions
This program to find the sum of list items is the same as the first example. However, we separated the python program logic using Functions.
# Python Program to find Sum of all Elements in a List def sum_of_list(NumList): total = 0 for j in range(Number): total = total + NumList[j] return total NumList = [] Number = int(input("Please enter the Total Number of List Elements : ")) for i in range(1, Number + 1): value = int(input("Please enter the Value of %d Element : " %i)) NumList.append(value) total = sum_of_list(NumList) print("\n The Sum of All Element in this List is : ", total)