Trusted answers to developer questions

How to take the average of a list in Python

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

The goal here is to find the average/mean of a list of numbers. The average is the sum of all the numbers in a list divided by its length.

svg viewer

Algorithms

Let’s have a look at a few of the algorithms used to compute the average for a list of numbers.

1. Using sum() and len() functions

An average can be computed using the sum() and len() functions on the list. sum() will return the sum of all the values in the list, which can be divided by the number of elements returned by the len() function. Take a look at the code below:

def Average(l):
avg = sum(l) / len(l)
return avg
my_list = [2,4,6,8,10]
average = Average(my_list)
print("Average of my_list is", average)

2. Using the mean() function

The mean() function in the python statistics library can be used to directly compute the average of a list. Take a look at​ the code below:

from statistics import mean
def Average(l):
avg = mean(l)
return avg
my_list = [2,4,6,8,10]
average = Average(my_list)
print "Average of my_list is", average

The ​statistics library needs to be installed in order to use the mean() function.

3. Using reduce() and lambda functions

The reduce method can be used to loop through the list and the sum can be computed in the lambda function. The number of elements can be obtained using len().

from functools import reduce
def Average(l):
avg = reduce(lambda x, y: x + y, l) / len(l)
return avg
my_list = [2,4,6,8,10]
average = Average(my_list)
print "Average of my_list is", average

RELATED TAGS

average
list
python
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?