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

  1. An array can be accessed by using indexes.
  2. So, first of all, we will find the length of the array.
  3. And then we iterate the for loop from 0 to the length array.
  4. And then we accessed the element of the array and add to him a variable named sum.
  5. 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

We simply use sum() function to find the sum of the array, sum() function is used to find the sum of the array.

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

Next Post Previous Post
No Comment
Add Comment
comment url