Use loop with a variable to sum all the numbers in a list in Python. Another option is to use the sum() function.
Python function to sum all the numbers in a list example
Simple example code using for loop, to sum up of a number of the given list.
num = [1, 2, 3, 4, 5] total = 0 for x in num: total += x print(total)
Using sum() method
a = [1, 2, 3, 4, 5] res = sum(a) print(res)
Using while() loop
total = 0 ele = 0 list1 = [11, 5, 17, 18, 23] while ele < len(list1): total = total + list1[ele] ele += 1 print(total)
list1 = [11, 5, 17, 18, 23] def sumOfList(lst, size): if size == 0: return 0 else: return lst[size - 1] + sumOfList(lst, size - 1) # Driver code total = sumOfList(list1, len(list1)) print(total)
Do comment if you have any doubts or suggestions on this Python sum topic
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.