Calculating Averages Made Easy: An Overview of 5 Python Methods

The Python ´mean()´ Function

The simplest method to calculate the average of a list is to use the statistics.mean() function. This function is available in Python 3 within the “statistics” module and accepts a list, tuple, or dataset containing numeric values as input.

Here is an example:

from statistics import mean 

inp_lst = [12, 45, 78, 36, 45, 237.11, -1, 88] 
list_avg = mean(inp_lst) 

print("Average value of the list:\n") 
print(list_avg) 
print("Average value of the list rounded to 3 decimal places:\n")
print(round(list_avg,3))

Using the Python ´sum()´ Function

Another method to calculate the average is to use the statistics.sum() function and the length of the list.

Here is an example:

from statistics import mean 

inp_lst = [12, 45, 78, 36, 45, 237.11, -1, 88]

sum_lst = sum(inp_lst)

lst_avg = sum_lst / len(inp_lst)
print("Average value of the list:\n") 
print(lst_avg) 
print("Average value of the list rounded to 3 decimal places:\n")
print(round(lst_avg,3))

Using Python ´reduce()´ and ´lambda()´

Another method to calculate the average of a list is to use the Python reduce() function in combination with the lambda() function.

Here is an example:

from functools import reduce 

inp_lst = [12, 45, 78, 36, 45, 237.11, -1, 88]

lst_len= len(inp_lst)

lst_avg = reduce(lambda x, y: x + y, inp_lst) / lst_len 
print("Average value of the list:\n") 
print(lst_avg) 
print("Average value of the list rounded to 3 decimal places:\n")
print(round(lst_avg,3))

Using the Python ´operator.add()´ Function

Another way to calculate the average using the operator module is to use the operator.add() function.

Here is an example:

from functools import reduce 
import operator

inp_lst = [12, 45, 78, 36, 45, 237.11, -1, 88]

lst_len = len(inp_lst)

lst_avg = reduce(operator.add, inp_lst) / lst_len 
print("Average value of the list:\n") 
print(lst_avg) 
print("Average value of the list rounded to 3 decimal places:\n")
print(round(lst_avg,3))

Using the NumPy ´average()´ Method

Finally, Python’s NumPy module provides a built-in numpy.average() method to calculate the average/mean of the data items present in the dataset or list.

Here is an example:

import numpy

inp_lst = [12, 45, 78, 36, 45, 237.11, -1, 88]

lst_avg = numpy.average(inp_lst)
print("Average value of the list:\n") 
print(lst_avg) 
print("Average value of the list rounded to 3 decimal places:\n")
print(round(lst_avg,3))

Conclusion

The choice of method for calculating the average depends on your requirements and preferences. Depending on the complexity of the task and the availability of the required modules, you can choose one of the methods mentioned above to find the average of your data.

Create a Free Account

Register now and get access to our Cloud Services.

Posts you might be interested in: