A list is a data structure that allows you to store more than one variable in a single variable. Let’s say you have elements of numeric type and wants to find the average of all the elements in it. Then how you will do that? In this tutorial, you will know how to average a list in python using various methods.
Methods to average a list in Python
Let’s know all the methods to find the mean or average of the list in Python.
Method 1: Using the built-in sum() function and len() function
We start by making a list, my_list, which has five numbers in it. Then we use the sum() function that will calculate the sum of all the numeric elements in the list. At last, we divide the calculated total sum by the number of items in the list (len(my_list)), which gives us the average.
Run the below lines of code to find the average of the list.
my_list = [10, 20, 30, 40, 50] average = sum(my_list) / len(my_list) print(average)
Method 2: Average the list using the statistics module
The mean() function from the statistics module takes a list of numbers as its argument and gives back the arithmetic mean of those numbers. In this example, we pass my_list to the mean() function and save the resulting value to the average. In the end, we output the average to the console, which displays 30.
import statistics my_list = [10, 20, 30, 40, 50] average = statistics.mean(my_list) print(average)
Method 3: Use the NumPy library
The NumPy library’s mean() function takes an array of numbers as its input and gives back the arithmetic average of those numbers. In this instance, we pass the my_list array to the mean() function of NumPy and save the output in the variable ‘average’. Lastly, we print the value of the average to the console, displaying 30.
import numpy as np my_list = [10, 20, 30, 40, 50] average = np.mean(my_list) print(average)
Method 4: Using the Pandas library
The Pandas library’s mean() function takes a list of numbers as input and produces the arithmetic mean of them. For example, we create a Pandas Series object from my_list using pd.Series(my_list) and then use the mean() function to calculate the average. The result is assigned to the variable average and printed to the console, which outputs 3.0.
import pandas as pd my_list = [10, 20, 30, 40, 50] average = pd.Series(my_list).mean() print(average)
There are numerous approaches to computing the mean of a list of numbers in Python. In the First method, you will use the sum() function to sum all the elements and divide the result by the total number of elements. In the second method, you will use the mean() function from the statistics module to calculate the arithmetic mean. All of these methods will provide identical results, which is the mean of the numbers in the list. The choice of the method is reliant on personal preference and the requirements of the specific task.