When dealing with a list of numbers, we might need to carry out statistical operations like finding the difference between the smallest and biggest, finding the minimum and maximum, finding the average, or just summing the numbers up. This tutorial is just going to focus on how to find the sum of a list in python.
We will show how to sum elements of a list in python-
- By using a
for loop
- And by using python’s
sum()
function.
Sum of a list using a for loop
This approach makes use of a for-loop
to add up all the items in a list. The next example illustrates this.
# create a list of numbers
num_list = [12, -5, 4, 7, -3, 9, 2]
# initialize the variable that will hold the final sum
sum_list = 0
# accumulate the sum into sum_list
for num in num_list:
sum_list += num
print(f"The sum of the list \n{num_list}\nis {sum_list}")
sum_list
was first initialized to 0, then each item in the loop was added to sum_list
.
Get the sum of a list in python using sum() function
Python has a built-in function, sum()
, that adds up all the numbers in a list.
# create a list of numbers
num_list = [12, -5.9, 4, 7, -3, 9, 2]
# call the sum() function to carry out the summation
sum_list = sum(num_list)
print(f"The sum of the list \n{num_list}\nis {sum_list}")
All the items in the list have to be numbers, otherwise, Python will raise a TypeError
.
How to sum a list of floats in Python?
Summing a list containing floats is similar to summing a list of numbers; just pass the list to the sum()
function, and let python do the rest. For example, look at the following code:
# create a list of floats
num_list = [0.3, -5.9, 4.7, 0.4, -3.4, 9.0, 2.3]
# call the sum() function to carry out the summation
sum_list = sum(num_list)
print(f"The sum of the list \n{num_list}\nis {sum_list}")
num_list
contains a list of float
numbers. To add all the numbers in the list, the code calls the sum()
function. the code produces the following output:
The sum of the list
[0.3, -5.9, 4.7, 0.4, -3.4, 9.0, 2.3]
is 7.3999999999999995
Conclusion
That’s all for this tutorial. It’s a rather simple task to find the sum of a list in python. Thanks for reading this tutorial, and check out our other tutorials on python such as-