Finding the average of a list
I have to find the average of a list in Python. This is my code so far
l = [15, 18, 2, 36, 12, 78, 5, 6, 9] print reduce(lambda x, y: x + y, l)
I've got it so it adds together the values in the list, but I don't know how to make it divide into them?
On Python 3.4+ you can use
l = [15, 18, 2, 36, 12, 78, 5, 6, 9] import statistics statistics.mean(l) # 20.11111111111111
On older versions of Python you can do
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
reduce. It is much slower and was removed in Python 3.
l = [15, 18, 2, 36, 12, 78, 5, 6, 9] sum(l) / len(l)
Read more... Read less...
Why would you use
reduce() for this when Python has a perfectly cromulent
print sum(l) / float(len(l))
float() is necessary to force Python to do a floating-point division.)
There is a statistics library if you are using python >= 3.4
You may use it's mean method like this. Let's say you have a list of numbers of which you want to find mean:-
list = [11, 13, 12, 15, 17] import statistics as s s.mean(list)
It has other methods too like stdev, variance, mode, harmonic mean, median etc which are too useful.
Instead of casting to float, you can add 0.0 to the sum:
def avg(l): return sum(l, 0.0) / len(l)