calculate sum of list elements in python

In this python example, first we define an array and calculate sum of that array using different methods like using loop and sum function.

Using Loop

In this method, we will create sum variable with 0 as it's value. Next, we will set loop on array or list. Then calculate and store element's value into sum variable.

Example - 1: using Loop

#sum of arry elements in python using loop
def arraySum(arr):
    sum = 0
    for i in arr:
        # shorthand of sum = sum + i
        sum += i
    return sum

print("Sum of array is ::",arraySum([1, 2, 3, 4, 5]))

Output :

Sum of array is :: 15

Here we have created arraySum function so we can use this functionality often in our program.

Using In-built sum() function

Python comes with an in-built solution for adding list or array and the sum() method simply returns the sum of each item of the gives list or array.

Example - 2: Using sum function

#sum of array using sum function

arr = [1, 2, 3, 4, 5]

print("Sum of array is ::",sum(arr))

Output :

Sum of array is :: 15

Here, we went through two different methods for sum the elements of an array however sum() function made our program faster and understandable.

Share your thoughts

Ask anything about this examples