Finding the average of a list Finding the average of a list python python

Finding the average of a list


On Python 3.4+ you can use statistics.mean()

l = [15, 18, 2, 36, 12, 78, 5, 6, 9]import statisticsstatistics.mean(l)  # 20.11111111111111

On older versions of Python you can do

sum(l) / len(l)

On Python 2 you need to convert len to a float to get float division

sum(l) / float(len(l))

There is no need to use reduce. It is much slower and was removed in Python 3.


l = [15, 18, 2, 36, 12, 78, 5, 6, 9]sum(l) / len(l)


You can use numpy.mean:

l = [15, 18, 2, 36, 12, 78, 5, 6, 9]import numpy as npprint(np.mean(l))