How can I calculate the average for a list of numbers?



In this exercise, the function written computes the average of two numbers passed as parameters. If the function were given a list of numbers, how could the average be calculated?


There are several ways to write a function to calculate the average of a list. In later versions of Python 3, there is a statistics library which contains a mean() function that can perform the calculation directly. Another simple way is to use the sum() and len() functions as shown below. Python 2 does not perform division using floating point unless instructed to do so by being given a floating point number (Python 3 does the conversion automatically) so the sum is cast to floating point.

def avg(numbers):
    return float(sum(numbers))/len(numbers)

Finally, it can be done using a for loop and variables to store the sum and length. This is more involved than the previous version but achieves the same result.

def avg(numbers):
    sum = 0
    count = 0
    for n in numbers:
        sum += n
        count += 1
    return float(sum) / count