Python Program to Find Sum of Array

In this blog, I'm going to tell how to find sum of array in python.




Example:
Input :  arr[] = {12, 3, 4, 15}
Output : 34


Method 1:

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) 
 

Output:
Sum of the array is 34


Method 2:

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)
  

Output:
Sum of the array is 34




AJ Blogs

Hello everyone, My name Arth and I like to write about what I learn. Follow My Website - https://sites.google.com/view/aj-blogs/home

Post a Comment

Previous Post Next Post
Best Programming Books

Facebook

AJ Facebook
Checkout Our Facebook Page
AJ Blogs
Checkout Our Instagram Page