Add integers given in a list and display their sum
Answers
Answer:
# Python program to find sum of elements in list
total = 0
# creating a list
list1 = [11, 5, 17, 18, 23]
# Iterate each element in list
# and add them in variable total
for ele in range(0, len(list1)):
total = total + list1[ele]
# printing total value
print("Sum of all elements in given list: ", total)
Output:
Sum of all elements in given list: 74
Answer:
Using a simple loop
The most basic solution is to traverse the list using a for/while loop, adding each value to the variable total. This variable will hold the sum of the list at the end of the loop. See the cøde below:
1 def sum_of_list(l):
2 total = 0
3 for val in l:
4 total = total + val
5 return total
6
7 my_list = [1,3,5,2,4]
8 print "The sum of my_list is", sum_of_list(my_list)