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 program allows users to enter the length of a List. Next, we used For Loop to add numbers to the list.
The sum function returns the sum of all the 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)

Without using sum() method
In this Python 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.
NumList = [] total = 0 Number = int(input("Please enter the Length : ")) 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)
Please enter the Length : 5
Please enter the Value of 1 Element : 10
Please enter the Value of 2 Element : 20
Please enter the Value of 3 Element : 30
Please enter the Value of 4 Element : 40
Please enter the Value of 5 Element : 55
The Sum of All Element in this List is : 155
Python Program to Calculate Sum of Elements in a List using While loop
This program to return the sum of list items is the same as the above. We just replaced the For Loop with a While loop.
NumList = [10, 20, -30, -40, 50, 100] total = 0 j = 0 while(j < len(NumList)): total = total + NumList[j] j = j + 1 print(total)
The sum of list items using a while loop output
110
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.
def sum_of_list(NumList): total = 0 for j in range(Number): total = total + NumList[j] return total NumList = [19, 11, 32, 86, 567, 32, 9] total = sum_of_list(NumList) print(total)
The sum of list items using functions output
756