Discover the sum of the array in Python: Here, we will figure out how to discover the sum of all elements of an array utilizing the python program?
Given a number array and we need to discover the sum of all elements in Python.
Finding the sum of array elements
There are two different ways to discover the sum of all array elements, 1) cross/get to every element and include the elements in a variable sum, lastly, print the sum. Furthermore, 2) discover the sum of array elements utilizing sum() work.
Example:
Input:
arr = [10, 20, 30, 40, 50]
Output:
sum = 150
Python program for the 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