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

Question

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?

Answer

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
7 Likes

You could simplify it further, as count is inherently equal to the length of the list. Thus we can rewrite the function, and shorten it a bit by using the len() method:

def avg(numbers):
  sum = 0
  for n in numbers:
    sum += n
  return sum / len(numbers)
3 Likes

I literally just wrote this and got the correct answer for both print statements. Think of the underscores as the tab in front of return:

def average(num1, num2):
__return (num1 + num2)/2

1 Like

but how you call this function?