Skip to main content
Calculate AVERAGE of a List in Python

Calculate AVERAGE of a List in Python

in this quick tutorial, you will learn how to calculate the average in Python. I’ll discuss the number of ways to calculate the average in python.

What’s Average

The Average function in Python is used to calculate the average of a list of values. The sum of the numbers in the list divided by the count of numbers in the list is the formula for calculating the average in Python.

You can calculate the list average in python in different ways as follows:

  • Calculate python Average by using the loop function.
  • By using sum() and len() built-in average function in Python
  • The mean() function is also used to calculate the average from the statistics module.
  • You can also use mean() method from numpy library

Python Average via Loop

Python for loop will iterate through the list’s members, adding and saving each number in the sumOfNumbers variable.

The average of a list in Python is determined using the built-in function len() and the sum num divided by the count of the numbers in the list.

Code Example:

def averageOfList(num):
    sumOfNumbers = 0
    for t in num:
        sumOfNumbers = sumOfNumbers + t
    avg = sumOfNumbers / len(num)
    return avg
  
print("The average of List is", averageOfList([20, 21, 56, 34, 19]))

Output:

The average of List is 30.0

Using sum() and len() functions

Python has a built-in function called sum() that returns the total of all list elements. The len() method in Python calculates the number of entries in a list. To calculate the list’s mean, we’ll combine these two built-in functions.

Code Example:

def averageOfList(num):
    avg = sum(num) / len(num)
    return avg


print("The average of List is", round(averageOfList([10, 11, 56, 34, 19]), 2))

Output:

average of List is 26.0

By numpy.mean() function

The average of the array elements is returned by the NumPy.mean() function. By default, the average is calculated over the flattened array; otherwise, it is calculated over the chosen axis.

Code Example:

from numpy import mean
number_list = [10, 11, 56, 34, 19]
avg = mean(number_list)
print("The average of List is ", round(avg, 2))

Output:

average of List is 26.0

Mean of Dictionary in Python

In Python, we may calculate mean using the statistics.mean() method. The mean function counts the keys as numbers and returns the Dictionary’s mean based on the keys.

Code Example:

import statistics

dictA = {1: 10, 2:11, 3:54, 4:16, 5:19}
print(statistics.mean(dictA))

Output:

3

Leave a Reply

Your email address will not be published. Required fields are marked *