How To Take The Average Of A List In Python

Calculating the average of a list of numbers is a common task in various programming scenarios, including data analysis, graph plotting, and estimation. In this tutorial, we will be learning how to take the average of a list in Python.

Python is a powerful and easy-to-learn programming language, which makes it an excellent choice for this task.

Step 1: Create a List of Numbers

First, let’s create a list of numbers that we want to find the average of. In this example, we will create a simple list of integers called numbers.

Step 2: Use the built-in sum() and len() functions in Python

Python has built-in functions sum() and len() which can be used to calculate the sum and length of a list, respectively. You can find the average by dividing the sum by the length of the list as follows:

The sum(numbers) function returns the total sum of all the elements in the list, while the len(numbers) function returns the length of the list (i.e., the number of elements). By dividing these two values, we get the average.

Step 3: Alternative method using the statistics module

Python comes with a built-in module called statistics that provides various statistical functions like mean, median, mode, and more. One such function is mean(), which directly calculates the average of any iterable. Here is how to use it:

Here, the statistics.mean() function calculates the average and returns the result.

Full Code

Here is the complete code for both methods:

Output:

3.0
3

Conclusion

In this tutorial, we learned how to calculate the average of a list in Python using two different methods. The first method uses built-in Python functions sum() and len(). The second method uses the statistics.mean() function from the built-in statistics module. Both methods produce the desired result, and you can choose the one that best fits your requirements.