The Python Oracle

Finding the average of a list

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: A Thousand Exotic Places Looping v001

--

Chapters
00:00 Question
00:18 Accepted answer (Score 802)
00:57 Answer 2 (Score 582)
01:08 Answer 3 (Score 318)
01:21 Answer 4 (Score 240)
01:39 Thank you

--

Full question
https://stackoverflow.com/questions/9039...

Accepted answer links:
[statistics.fmean]: https://docs.python.org/3/library/statis...
[statistics.mean]: https://docs.python.org/3/library/statis...

Answer 3 links:
[numpy.mean]: http://docs.scipy.org/doc/numpy/referenc...

Answer 4 links:
[Python 3.4+]: http://docs.python.org/dev/whatsnew/3.4....
[mean()]: http://docs.python.org/dev/library/stati...
[statistics]: http://docs.python.org/dev/library/stati...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list #average #mean #reduce

#avk47



ACCEPTED ANSWER

Score 858


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



ANSWER 2

Score 596


xs = [15, 18, 2, 36, 12, 78, 5, 6, 9]
sum(xs) / len(xs)



ANSWER 3

Score 327


Use numpy.mean:

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

import numpy as np
print(np.mean(xs))



ANSWER 4

Score 51


Why would you use reduce() for this when Python has a perfectly cromulent sum() function?

print sum(l) / float(len(l))

(The float() is necessary in Python 2 to force Python to do a floating-point division.)