pythonlistaveragemeanreduce

Finding the average of a list


How do I find the arithmetic mean of a list in Python? For example:

[1, 2, 3, 4]  ⟶  2.5

Solution

  • For Python 3.8+, use statistics.fmean for numerical stability with floats. (Fast.)

    For Python 3.4+, use statistics.mean for numerical stability with floats. (Slower.)

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

    For older versions of Python 3, use

    sum(xs) / len(xs)
    

    For Python 2, convert len to a float to get float division:

    sum(xs) / float(len(xs))