Python Program to find sum of array
Given an array of integers, find the sum of its elements.
Examples:
Input : arr[] = {1, 2, 3}
Output : 6
Explanation: 1 + 2 + 3 = 6Input : arr[] = {15, 12, 13, 10}
Output : 50
Method 1: Iterating through the array and adding each element to the sum variable and finally displaying the sum.
Python3
# Python 3 code to find sum # of elements in given array def _sum(arr): # initialize a variable # to store the sum # while iterating through # the array later sum = 0 # iterate through the array # and add each element to the sum variable # one at a time for i in arr: sum = sum + i return ( sum ) # driver function arr = [] # input values to list arr = [ 12 , 3 , 4 , 15 ] # calculating length of array n = len (arr) ans = _sum(arr) # display sum print ( 'Sum of the array is ' , ans) |
Sum of the array is 34
Time complexity: O(n),
Auxiliary Space: O(1)
Method 2: Using the built-in function sum(). Python provides an inbuilt function sum() which sums up the numbers in the list.
Syntax:
sum(iterable)
iterable: iterable can be anything list, tuples or dictionaries, but most importantly it should be numbered.
Python3
# Python 3 code to find sum # of elements in given array # driver function arr = [] # input values to list arr = [ 12 , 3 , 4 , 15 ] # sum() is an inbuilt function in python that adds # all the elements in list,set and tuples and returns # the value ans = sum (arr) # display sum print ( 'Sum of the array is ' , ans) |
Sum of the array is 34
Time complexity: O(n)
Auxiliary Space: O(1)
Method 2: Using the reduce method. Array.reduce() method is used to iterate over the array and get the summarized result from all elements of array.
Syntax:
reduce( function, Array );
Python
from functools import reduce # Python 3 code to find sum # of elements in given array def _sum(arr): # iterate over array # using reduce and get # sum on accumulator sum = reduce ( lambda a, b: a + b, arr) return ( sum ) # driver function arr = [] # input values to list arr = [ 12 , 3 , 4 , 15 ] # calculating length of array n = len (arr) ans = _sum(arr) # display sum print ( 'Sum of the array is ' , ans) |
('Sum of the array is ', 34)
Time complexity : O(n)
Auxiliary Space : O(1)
Example: Using enumerate function
Python3
list1 = [ 12 , 3 , 4 , 15 ];s = 0 for i,a in enumerate (list1): s + = a print (s) |
34
Time complexity: O(n)
Auxiliary Space: O(1)
Please refer complete article on Program to find sum of elements in a given array for more details!
Please Login to comment...