Home »
Python »
Python programs
Python program to find the sum of all elements of an array
Find the sum of the array in Python: Here, we are going to learn how to find the sum of all elements of an array using the python program?
Submitted by IncludeHelp, on May 26, 2019
Given an integer array and we have to find the sum of all elements in Python.
Finding the sum of array elements
There are two ways to find the sum of all array elements, 1) traverse/access each element and add the elements in a variable sum, and finally, print the sum. And, 2) find the sum of array elements using sum() function.
Example:
Input:
arr = [10, 20, 30, 40, 50]
Output:
sum = 150
Python program for sum of the array elements
# Python program for sum of the array elements
# functions to find sum of elements
# Approach 1
def sum_1(arr):
result = 0
for x in arr:
result += x
return result
# Approach 2
def sum_2(arr):
result = sum(arr)
return result
# main function
if __name__ == "__main__":
arr = [10, 20, 30, 40, 50]
print ('sum_1: {}'.format(sum_1(arr)))
print ('sum_2: {}'.format(sum_2(arr)))
Output
sum_1: 150
sum_2: 150
Python Array Programs »
TOP Interview Coding Problems/Challenges