On Python 3.8+, with floats, you can use statistics.fmean
as it’s faster with floats.
On Python 3.4+, you can use statistics.mean
:
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
import statistics
statistics.mean(l) # = 20.11111111111111
On older versions of Python you can:
sum(l) / len(l)
On Python 2, you need to convert len
to a float to get float division
sum(l) / float(len(l))
There is no need to use functools.reduce
as it is much slower.