Find the Mean/Average of a Number List in Python
To my knowledge, there is no built-in function in Python to find the mean of a list of numbers. You can use statistics packages to do this, such as statpy, but if you just want a lightweight solution to do the trick you can use the function below. Note that on the first line I am converting the numbers to floats because if you were to pass it a list of integers, it would not compute the mean properly.
def mean(numberList): if len(numberList) == 0: return float('nan') floatNums = [float(x) for x in numberList] return sum(floatNums) / len(numberList)
couldnt you just do
def mean(numberList):
return float(sum(floatNums)) / len(numberList)
pk is right, python has a built in sum() function, although his code example is sloppy.
def mean(nums):
if len(nums):
return float( sum(nums) / len(nums))
else:
return 0.0
hah, division by zero. how embarrasing.
Your function has input argument numberList but refers to it as floatNums (a variable that is defined in another post therefore outside the scope of your function). There will never be a division by zero because the interpreter will not be able to proceed to the division.
oh wow. that’s a shocker
dae, you should check your own code.
It should be:
return float( sum(nums) ) / len(nums)
What you had will first calculate sum/len as an integer and then convert it to a float. You end up with interger_result.0
Is there a definition for mean of no values?
It is not obvious to me that the mean of an empty sequence is 0.0, perhaps division by zero (or a specific exception) is reasonable. It might depend on the use of the function.
Since division by 0 triggers an exception in Python, it might be a good idea to not check in many cases, and use that as a precondition. In other languages were division by 0 will yield NAN and INF which can then be used silently, the check is more important.
Yeah, that’s a valid point. It should be “not a number.” I’ve updated the code based on your suggestion.
For python 2.2-2.7, you can just do:
from ___future___ import division
And then sum(nums)/len(nums) will work as expected – no need to convert anything to a float. This is the default in 3.0 on.
This code worked.
Thanks a lot!