The Python Oracle

Finding the average of a list

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Forest of Spells Looping

--

Chapters
00:00 Finding The Average Of A List
00:11 Accepted Answer Score 853
00:47 Answer 2 Score 595
00:56 Answer 3 Score 324
01:08 Answer 4 Score 243
01:21 Answer 5 Score 51
01:37 Thank you

--

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

--

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