Calculating arithmetic mean (one type of average) in Python Calculating arithmetic mean (one type of average) in Python python python

Calculating arithmetic mean (one type of average) in Python


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().


NumPy has a numpy.mean which is an arithmetic mean. Usage is as simple as this:

>>> import numpy>>> a = [1, 2, 4]>>> numpy.mean(a)2.3333333333333335


Use statistics.mean:

import statisticsprint(statistics.mean([1,2,4])) # 2.3333333333333335

It's available since Python 3.4. For 3.1-3.3 users, an old version of the module is available on PyPI under the name stats. Just change statistics to stats.


matomo