If we look at the official documentation, we can realize that Python does not come with a native mean() or average() function, as it does with sum() or len(). Therefore, calculating the average of a list in Python is not as easy as it may sound.
Let’s have a look at the options we have at our disposal to achieve this operation.
Table of Contents
Use len() and sum() to calculate the average of a list
One of the easiest options is to use the sum() and len() functions. Indeed, the average of a list is equal to the sum of its elements divided by its length. Easy, right?
my_list = [1,2,3,4,5,6,7]
avg = sum(my_list) / len(my_list)
print(f'The average is {avg}.')
Code language: Python (python)
Output:
The average is 4.0.
Code language: CSS (css)
While this is the option I’d use in most cases, let’s explore other approaches.
Use a while loop to calculate the mean of a list
This approach is more naive and add complexity to the solution of our problem. That being said, if you are starting with Python, I’d try to avoid the built-in function as much as you can to understand the underlying logics they use.
my_list = [1,2,3,4,5,6,7]
#variable to sum values
sum_list = 0
#variable to count values
n_elements = 0
#start a while loop
while my_list:
#add first element to our sum_list variable
sum_list += my_list[0]
#add 1 to our n_elements variable
n_elements += 1
#remove first element of our list
my_list = my_list[1:]
#calculate average
avg_list = sum_list/n_elements
#print it
print(avg_list)
Code language: Python (python)
Output:
4.0
Code language: Python (python)
Use reduce() to calculate the average of a list
Reduce() is a function from the functools library that allows us to apply a function cumulatively to the items of an iterable (a list in our case), from left to right, to reduce the iterable to a single value. Under the hood, it uses a simple code:
def reduce(function, iterable, initializer=None):
it = iter(iterable)
if initializer is None:
value = next(it)
else:
value = initializer
for element in it:
value = function(value, element)
return value
Code language: Python (python)
Applied to our example, we can use a lambda function to calculate the sum of our list and then divide it by its length.
from functools import reduce
my_list = [1,2,3,4,5,6,7]
sum_list = reduce(lambda a,b:a+b, my_list)
avg_list = sum_list/len(my_list)
print(avg_list)
Code language: Python (python)
Again, not as easy as our first option, but a good example of how you can use the reduce() function.
Use mean() from statistics to calculate the mean of a list
Even if Python doesn’t come directly with a mean function, you can import a function from the statistics library. It would save you creating a custom function.
from statistics import mean
my_list = [1,2,3,4,5,6,7]
avg_list = mean(my_list)
print(avg_list)
Code language: Python (python)
Output:
4.0
Code language: Python (python)