Python program to find the sum of array (list) elements

ython program to find the sum of array (list) elements

In this tutorial, we will learn writing python program to create an array (list in case of python) and calculate the sum of elements stored in the array (list).

Problem Statement

Our problem statement is like, our program should take the array size from the user and then the elements of the array (list). After taking the input, It will calculate the sum of elements of the input array (list) and print it as output.

For example:

Case 1: if the user inputs 4 as array (list) size and the array (list) elements as 1,2,3,4.

                                    The output should be 10.

Case 2: if the user inputs 5 as array (list) size and the array (list) elements as 9,8,7,6,5.

                                    The output should be 35.

Our logic to find the sum of array (list) elements

  • Our program will take input to fix the size of the array (list).
  • Create a variable named ‘sum’ and assign it with value 0.
  • Then our program will run for a ‘for loop’ to take the inputs from the user. The inputs will be the elements (or the content) of the array (list). And also adding the elements into the variable sum.
  • Print the variable sum as the output

Algorithm to find the sum of array (list) elements

Step 1: Start

Step 2: take an input from the user (let’s say size).

Step 3: Create an empty list and a variable sum with value assign is 0.

Step 4: for i in range(0,size):

                    elem=int(input(“Please give value for index “+str(i)+”: “))

                    arr.append(elem)

                   sum+=elem

Step 5: print sum

Step 6: Stop

Python code to find the sum of array (list) elements

Output 1:

calculate the sum of array element in python

Explanation:

For the input array (list) [23, 12, 2, 4, 6],

value of sum = 23 + 12 + 2 + 4 + 6 = 47.

Output 2:

python program to calculate the sum of array element

Explanation:

For the input array (list) [19, 81, 67, 09, 1, 12],

value of sum =19 + 81 + 76 + 9 + 1 + 12 = 189.