patternpythonCritical
Finding the average of a list
Viewed 0 times
averagelistfindingthe
Problem
How do I find the arithmetic mean of a list in Python? For example:
[1, 2, 3, 4] ⟶ 2.5Solution
For Python 3.8+, use
For Python 3.4+, use
For older versions of Python 3, use
For Python 2, convert
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.11111111111111For 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.11111111111111sum(xs) / len(xs)sum(xs) / float(len(xs))Context
Stack Overflow Q#9039961, score: 916
Revisions (0)
No revisions yet.