When working with lists of numbers in Python, it's often necessary to calculate their average. The average, also known as the arithmetic mean, provides a measure of central tendency and is widely used in data analysis, statistics, and everyday programming tasks.
In this blog post, we'll showcase three different methods for finding the average of a list of numbers in Python, from simple arithmetic to powerful built-in functions and libraries.
Method 1: Compute it yourself
In our first method, we simply write a function that sums up the numbers in a list and divides it by the count to obtain the average:
The output is:
Note that the output is a floating point number, the result of the division. Also note that the above function will not work if the list is empty because you will get a division by zero. You will need to trap for that condition inside the average() function.
Method 2: Use statistics.mean()
Python provides the statistics module, which offers a wide range of statistical functions, including calculating the average. Here's an example using the statistics.mean() function:
The output is as expected:
Once again note that this will not work if the list is empty and will throw an error. Nevertheless, the statistics.mean() function automatically computes the average of a list of numbers, saving you the hassle of performing manual calculations.
Method 3: Use numpy.average()
The numpy.average() function works very similar to the stat.mean() function:
The output is:
Again this will not work if the list is empty.
Calculating the average of a list of numbers is a common task in Python programming. In this blog post, we have seen various methods for finding the average, including basic arithmetic, utilizing the statistics module, and using the numpy module for more advanced numerical computations. By understanding these techniques, you can efficiently compute the average of any list of numbers in Python. Remember to handle edge cases, such as empty lists, to ensure your code is robust.
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.