Finding the average of a list
xs = [15, 18, 2, 36, 12, 78, 5, 6, 9]
sum(xs) / len(xs)
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))