First Declare a new variable with 0 and then iterate over the list by reassigning the variable to its value plus the current number to sum a list in Python using for loop.
Sum a list in python using for loop
Simple example code.
my_list = [2, 4, 6, 8]
sum = 0
for num in my_list:
sum += num
print("Sum", sum)
Output:
This code achieves the same result:
total += num
total = total + num
Looping through a nested list and summing all elements of each internal list in Python
All_slips = [[1,2,3,4],[1,3,5,7],[1,2,7,9]]
summed_list = []
for sublist in All_slips:
summed_list.append(sum(sublist))
That’s all. You can also employ a list comprehension.
summed_list = [sum(sublist) for sublist in All_slips]
Function for it
Encapsulate that for general use, e.g. in a function:
def sum_list(l):
sum = 0
for x in l:
sum += x
return sum
Now you can apply this to any list. Examples:
l = [1, 2, 3, 4, 5]
sum_list(l)
l = list(map(int, input("Enter numbers separated by spaces: ").split()))
sum_list(l)
Do comment if you have any doubts or suggestions on this Python list topic
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.