HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonCritical

Finding the average of a list

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
averagelistfindingthe

Problem

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

Code Snippets

xs = [15, 18, 2, 36, 12, 78, 5, 6, 9]

import statistics
statistics.mean(xs)  # = 20.11111111111111
sum(xs) / len(xs)
sum(xs) / float(len(xs))

Context

Stack Overflow Q#9039961, score: 916

Revisions (0)

No revisions yet.