To calculate the sum of a list of numbers in Python, the easiest way is with the sum() function.
l = [1,2,3,4,5,6,7]
print(sum(l))
#Output:
28
You can also use a for loop to sum the numbers of a list.
l = [1,2,3,4,5,6,7]
s = 0
for num in l:
s = s + num
print(s)
#Output:
28
When working with collections of data in Python, the ability to summarize the data easily is valuable.
One such case is if you want to get the sum of a list of numbers.
To calculate the sum of a list of numbers in Python, the easiest way is with the sum() function.
sum() returns the sum of a list of numbers.
Below shows you how to get the sum of a list of numbers in Python with sum().
l = [1,2,3,4,5,6,7]
print(sum(l))
#Output:
28
Using For Loop to Get Sum of List in Python
Another way you can add numbers of a list together is with a for loop.
To add the numbers of a list up, initialize a variable which will keep the running sum and then add each element to the running sum.
Below shows you how to get the sum of a list of numbers in Python with a for loop.
l = [1,2,3,4,5,6,7]
s = 0
for num in l:
s = s + num
print(s)
#Output:
28
Hopefully this article has been useful for you to learn how to get the sum of a list in Python.