Learnitweb

Python Program to find sum of numbers in an array

Approach 1

In the first approach we’ll loop through the elements of the array and add every element to the sum which is initialized to 0.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
arr = [1,2,3,4,8,9]
sum = 0
for element in arr:
sum = sum + element
print("sum of array elements is ", sum)
arr = [1,2,3,4,8,9] sum = 0 for element in arr: sum = sum + element print("sum of array elements is ", sum)
arr = [1,2,3,4,8,9]
sum = 0
for element in arr:
    sum = sum + element

print("sum of array elements is ", sum)

Output

sum of array elements is  27

Approach 2

In the second approach, we’ll use the inbuilt method sum() to calculate the sum of elements of an array.

Please note that you can pass any iterable to the sum() function.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
sum = sum(arr)
print("sum of array elements is ",sum)
sum = sum(arr) print("sum of array elements is ",sum)
sum = sum(arr)
print("sum of array elements is ",sum)

Output

sum of array elements is  27