Calculating arithmetic mean (one type of average) in Python

jrdioko picture jrdioko · Oct 10, 2011 · Viewed 637.4k times · Source

Is there a built-in or standard library method in Python to calculate the arithmetic mean (one type of average) of a list of numbers?

Answer

NPE picture NPE · Oct 10, 2011

I am not aware of anything in the standard library. However, you could use something like:

def mean(numbers):
    return float(sum(numbers)) / max(len(numbers), 1)

>>> mean([1,2,3,4])
2.5
>>> mean([])
0.0

In numpy, there's numpy.mean().