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