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

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?

This question is related to python math statistics average mean

The answer is


def avg(l):
    """uses floating-point division."""
    return sum(l) / float(len(l))

Examples:

l1 = [3,5,14,2,5,36,4,3]
l2 = [0,0,0]

print(avg(l1)) # 9.0
print(avg(l2)) # 0.0

Others already posted very good answers, but some people might still be looking for a classic way to find Mean(avg), so here I post this (code tested in Python 3.6):

def meanmanual(listt):

mean = 0
lsum = 0
lenoflist = len(listt)

for i in listt:
    lsum += i

mean = lsum / lenoflist
return float(mean)

a = [1, 2, 3, 4, 5, 6]
meanmanual(a)

Answer: 3.5

from statistics import mean
avarage=mean(your_list)

for example

from statistics import mean

my_list=[5,2,3,2]
avarage=mean(my_list)
print(avarage)

and result is

3.0

You don't even need numpy or scipy...

>>> a = [1, 2, 3, 4, 5, 6]
>>> print(sum(a) / len(a))
3

I always supposed avg is omitted from the builtins/stdlib because it is as simple as

sum(L)/len(L) # L is some list

and any caveats would be addressed in caller code for local usage already.

Notable caveats:

  1. non-float result: in python2, 9/4 is 2. to resolve, use float(sum(L))/len(L) or from __future__ import division

  2. division by zero: the list may be empty. to resolve:

    if not L:
        raise WhateverYouWantError("foo")
    avg = float(sum(L))/len(L)
    

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

Instead of casting to float you can do following

def mean(nums):
    return sum(nums, 0.0) / len(nums)

or using lambda

mean = lambda nums: sum(nums, 0.0) / len(nums)

UPDATES: 2019-12-15

Python 3.8 added function fmean to statistics module. Which is faster and always returns float.

Convert data to floats and compute the arithmetic mean.

This runs faster than the mean() function and it always returns a float. The data may be a sequence or iterable. If the input dataset is empty, raises a StatisticsError.

fmean([3.5, 4.0, 5.25])

4.25

New in version 3.8.


Use statistics.mean:

import statistics
print(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.


The proper answer to your question is to use statistics.mean. But for fun, here is a version of mean that does not use the len() function, so it (like statistics.mean) can be used on generators, which do not support len():

from functools import reduce
from operator import truediv
def ave(seq):
    return truediv(*reduce(lambda a, b: (a[0] + b[1], b[0]), 
                           enumerate(seq, start=1), 
                           (0, 0)))

If you're using python >= 3.8, you can use the fmean function introduced in the statistics module which is part of the standard library:

>>> from statistics import fmean
>>> fmean([0, 1, 2, 3])
1.5

It's faster than the statistics.mean function, but it converts its data points to float beforehand, so it can be less accurate in some specific cases.

You can see its implementation here


Use scipy:

import scipy;
a=[1,2,4];
print(scipy.mean(a));

def list_mean(nums):
    sumof = 0
    num_of = len(nums)
    mean = 0
    for i in nums:
        sumof += i
    mean = sumof / num_of
    return float(mean)

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to math

How to do perspective fixing? How to pad a string with leading zeros in Python 3 How can I use "e" (Euler's number) and power operation in python 2.7 numpy max vs amax vs maximum Efficiently getting all divisors of a given number Using atan2 to find angle between two vectors How to calculate percentage when old value is ZERO Finding square root without using sqrt function? Exponentiation in Python - should I prefer ** operator instead of math.pow and math.sqrt? How do I get the total number of unique pairs of a set in the database?

Examples related to statistics

Function to calculate R2 (R-squared) in R pandas: find percentile stats of a given column What exactly does numpy.exp() do? Find p-value (significance) in scikit-learn LinearRegression How to plot ROC curve in Python Pandas - Compute z-score for all columns Calculating percentile of dataset column How to normalize an array in NumPy to a unit vector? How to find row number of a value in R code np.mean() vs np.average() in Python NumPy?

Examples related to average

np.mean() vs np.average() in Python NumPy? Take a list of numbers and return the average How to manipulate arrays. Find the average. Beginner Java Finding moving average from data points in Python Calculating average of an array list? SQL query with avg and group by How to compute the sum and average of elements in an array? Finding the average of a list Trying to get the average of a count resultset Calculating arithmetic mean (one type of average) in Python

Examples related to mean

Python Pandas : group by in group by and average? Mean of a column in a data frame, given the column's name calculate the mean for each column of a matrix in R np.mean() vs np.average() in Python NumPy? Mean Squared Error in Numpy? Calculate mean across dimension in a 2D array Calculating arithmetic mean (one type of average) in Python Calculate mean and standard deviation from a vector of samples in C++ using Boost