Javaexercise.com

Program To Find Sum Of Array/list Elements In Python

In this article, we will learn to find the sum of an array/list in Python.

Python does not use an array instead uses a list to store elements. So, here, we will find sum of the list elements. There are two approaches to calculating the sum.

  1. Using for-each loop

  2. Using built-in sum() method

Python Program to Find Sum of Array/List Using for-each loop

In this approach, we maintain a variable called sum and initialize it 0. We loop through the array/list and add each value in the list to the sum one by one. When the loop terminates the sum of all elements is store in the sum variable. Look at the code below:

# Take a list
je_array = [ 1, 3, 43, -6, 321, 4 ]
# Initialize with zero
je_sum = 0
# Traverse elements and calculate sum
for je_ele in je_array:
 je_sum = je_sum + je_ele;
# Display result
print("Sum ",je_sum)

Output:

366

Python Program to Find Sum of Array/List Using sum() method

Python provides a built-in sum() method that takes a list as an argument and returns the sum of the elements in the array. Look at the code below:

# Take a list
je_array = [ 1, 3, 43, -6, 321, 4 ]

# Calculate sum using built-in sum() method
je_sum = sum(je_array)
# Display result
print("Sum ",je_sum)

Output:

366