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.
Using for-each loop
Using built-in sum() method
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 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