How to Find the Average of a List in Python

If you're using the programming language called Python to do math or statistical computing, you may need to take the average of numbers in a list at some point. There are several ways to do this, including computing the average by looping over the list and using library functions to find the mean of a set of numbers.

Image Credit: matejmo/iStock/GettyImages

Python Average Via Loop

The average, or mean, of a set of numbers usually refers to the sum of all the numbers divided by the amount of numbers in the list. This gives the arithmetic mean, which can be useful in a variety of statistical applications and informal contexts.

The programming language Python makes it relatively easy to step, or loop, through the elements of a list and compute some property for each of them. Python includes a variety of types of loop, including "while" loops that continue until a condition is no longer true and "for" loops that execute code once on each element of a list.

A "for" loop is probably the easiest loop to use in Python for the mean of a list. Set a variable equal to zero and iterate over each element of the list, adding its value to the new variable. When the loop is done, compute the length of the list using Python's built-in "len" function. Divide the sum by the length of the list.

Dealing With Rounding

If the list contains all integers, multiply the list by the constant "1.0" to coerce it to a decimal number so Python does not round the result to the nearest integer. You may want to use Python's built-in "Decimal" class to control how much rounding Python does of the result.

This process is the same in either Python 2 or Python 3 versions of the language.

Using the NumPy Mean Function

In some cases, you may not want to implement your code to perform a common operation like taking the mean of numbers in Python.

You can use a variety of add-on libraries to Python to compute the mean and other statistical functions. A common one is the NumPy scientific computing library, which is a free library. You can pass a list or array of numbers to the "numpy.mean" function included in the library, and it returns the mean of the numbers you pass.

NumPy can be installed on most modern operating systems and versions of Python. NumPy can also be used with Python for a standard deviation computation using its "numpy.std" function.

references