Code Comments

Code Comments

Tips and short tutorials on various programming technologies

Code Comments RSS Feed
 
 
 
 

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)

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

  1. 1
    pk:

    couldnt you just do

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

  2. 2
    dae:

    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. 3
    pk:

    hah, division by zero. how embarrasing.

Leave a Reply