In this article, we will learn to find the sum of the elements in a List using the python program.
We find the sum of the elements in the list using 3 methods:
- Using loop
- Using Recursion
- Using sum() function
Using loop
Explanation
Using iteration of the list, we add the elements one by one in a variable and lastly print the sum of the elements.
Program
1
2
3
4
5
6
7
8
9
10
11
12
13
14 | # List
List = [1, 2, 3, 4, 5, 6]
# init the sum variable
sum = 0
# iterate the list
for ele in List:
# update the sum with elements of the list
# add all the elements in sum variable
sum += ele
# prin the sum of the elements
print("The sum of the elements is:",sum)
|
Output
The sum of the elements is: 21
Using Recursion
Explanation
Using recursion we find the sum of the elements of the list. Ada last elements and update the size value to -1 and add one by one.
Program
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 | # List
list = [1, 2, 3, 4, 5, 6]
# size of the list
size = len(list)
# make a function sum_of_elements
def sum_of_elements(list, size):
if size == 0:
return 0
else:
# add all the elements by recursion
return list[size-1] + sum_of_elements(list, size-1)
sum = sum_of_elements(list, size)
# prin the sum of the elements
print("The sum of the elements is:",sum)
|
Output
The sum of the elements is: 21
Using sum() function
Explanation
The sum() function is used to find the sum of all elements.
Program
1
2
3
4
5
6
7
8 | # List
list = [1, 2, 3, 4, 5, 6]
# use sum() functon to add all the elements
total = sum(list)
# prin the sum of the elements
print("The sum of the elements is:",total)
|
Output
The sum of the elements is: 21