The formula to calculate average is done by calculating the sum of the numbers in the list divided by the count of numbers in the list.

The average of a list can be done in many ways listed below:

  • Python Average by using the loop
  • By using sum() and len() built-in functions from python
  • Using mean() function to calculate the average from the statistics module.
  • Using mean() from numpy library

In this Python tutorial, you will learn:

Python Average via Loop

In this example, we have initialized the variable sum_num to zero and used for loop. The for-loop will loop through the elements present in the list, and each number is added and saved inside the sum_num variable. The average is calculated by using the sum_num divided by the count of the numbers in the list using len() built-in function.

Code Example:

def cal_average(num):
    sum_num = 0
    for t in num:
        sum_num = sum_num + t           

    avg = sum_num / len(num)
    return avg

print("The average is", cal_average([18,25,3,41,5]))

Output:

The average is 18.4

Using sum() and len() built-in functions

In this example the sum() and len() built-in functions are used. It is a straight forward way to calculate the average as you don't have to loop through the elements, and also, the code size is reduced. The average can be calculated with just one line of code as shown below.

Program Example:

# Example to find average of list
number_list = [45, 34, 10, 36, 12, 6, 80]
avg = sum(number_list)/len(number_list)
print("The average is ", round(avg,2))

Output:

The average is  31.86

Using mean function from statistics module

You can easily calculate the "average" using the mean function from the statistics module. Example shown below

# Example to find the average of the list
from statistics import mean
 
number_list = [45, 34, 10, 36, 12, 6, 80]
avg = mean(number_list)
print("The average is ", round(avg,2))

Output:

The average is  31.86

Using mean() from numpy library

Numpy library is commonly used library to work on large multi-dimensional arrays. It also has a large collection of mathematical functions to be used on arrays to perform various tasks. One important one is the mean() function that will give us the average for the list given.

Code Example:

# Example to find avearge of list
from numpy import mean
number_list = [45, 34, 10, 36, 12, 6, 80]
avg = mean(number_list)
print("The average is ", round(avg,2))

Output:

C:\pythontest>python testavg.py
The average is  31.86

Summary:

  • The formula to calculate average is done by calculating the sum of the numbers in the list divided by the count of numbers in the list.
  • The average of a list can be done in many ways i.e
    • Python Average by using the loop
    • By using sum() and len() built-in functions from python
    • Using mean() function to calculate the average from the statistics module.
    • Using mean() from numpy library

 

YOU MIGHT LIKE: