Find sum of array in python | Python program to find sum of array
In this article, we will learn to find the sum of the array using the python program.
So, we find the sum of the array in python using two methods
- using for loop
- using the sum() function
Method 1: Using for loop
Explanation
- An array can be accessed by using indexes.
- So, first of all, we will find the length of the array.
- And then we iterate the for loop from 0 to the length array.
- And then we accessed the element of the array and add to him a variable named sum.
- Then, we print the sum variable.
Program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | # find the sum of the arr in python # arr arr = [2,4,6,8] #length of the arr using len() function length = len(arr) sum = 0 # initally sum = 0 # iterate the for loop from 0 to length of arr for i in range(0, length): sum = sum + arr[i] # add element of array # print the sum print(sum) |
Output
20
Method 2: Using sum() function
Explanation
Program
1 2 3 4 5 6 7 8 9 | # find the sum of the arr in python # arr arr = [2,4,6,8] # used sum() fuction s = sum(arr) # print the sum print(s) |
Output
20