Python program to find the sum of elements of List

Python program to find the sum of elements of List.

Problem Definition

In this program reads the array elements of the list. Then finds the sum of elements of the list and finally prints the sum.

Step by Step solution to Python program to find the sum of elements of List

1. Create a empty list to store the elements of list and sum variable with 0.

2. Read the umber of elements in the list.

3. Read the elements of list one by one from standard keyboard.

4. Loop over the elements of list, add the element to partial sum.

5. Finally, print the list elements and sum of elements of list.

Program Source code using inbuilt list function

s = 0
l1 = list()

n = int(input ("Enter the number of elements:"))
for i in range(n):
    ele = int (input ("Enter the element: "))
    l1.append(ele)

s = sum(l1)
print ("Sum of elements of ", l1, "is: ", s)

Detailed Program Explanation

First, create a variable s to store the partial sum and create an empty list using list function store the elements of the list.

READ  Structured Query Language with a python program

Read the number of elements in the list using the input function. User must enter a numeric value, otherwise, it generates an error.

Loop over the number of elements, read the elements of list one by one using input function.

Finally, calculate the sum of elements of a list using the sum function of the list and print the list and the sum of elements of the list.

Program Source code without using inbuilt list function

s = 0
l1 = list()

n = int(input ("Enter the number of elements:"))
for i in range(n):
    ele = int (input ("Enter the element: "))
    l1.append(ele)

for ele in l1:
    s = s + ele
print ("Sum of elements of ", l1, "is: ", s)

Detailed Program Explanation

First, create a variable to store the partial sum and create an empty list using the list function store the elements of the list.

Read the number of elements in the list using the input function. User must enter a numeric value, otherwise, it generates an error.

READ  I J K and L character pattern programs in Java

Loop over the number of elements, read the elements of list one by one using input function.

Loop over the elements of a list using for loop, find the partial sum of the list.

Finally, calculate the sum of elements of a list using the sum function of the list and print the list and the sum of elements of the list.

The output of the Python program to find the sum of elements of List

Enter the number of elements:4
Enter the element: 10
Enter the element: 20
Enter the element: 30
Enter the element: 40
Sum of elements of  [10, 20, 30, 40] is:  100

If you like the tutorial please share with your friends and share your opinion in comment box.