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)

5 Responses to “Find the Mean/Average of a Number List in Python”

  1. couldnt you just do

    def mean(numberList):
    return float(sum(floatNums)) / len(numberList)

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

  3. hah, division by zero. how embarrasing.

  4. not division by zero yet on May 13th, 2010 at 9:32 am

    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.

  5. oh wow. that’s a shocker

Leave a Reply