---Advertisement---

 How to Calculate Average of List in Python: 4 Easy Methods with Examples

By Bhavani

Updated On:

---Advertisement---
 How to Calculate Average of List in Python

👉How to Calculate Average of List in Python: Step-by-Step Guide

How to Calculate Average of List in Python: Calculating the average of a list in Python is a common task in programming. Python provides multiple ways to achieve this efficiently. Below are four effective methods to calculate the average in Python.

👉Table of Contents

How to Calculate Average of List in Python

  • Method 1: Using a Loop
  • Method 2: Using sum() and len()
  • Method 3: Using statistics.mean()
  • Method 4: Using numpy.mean()

👉Method 1: Using a Loop

In this method, we use a for loop to iterate through the list and calculate the total sum. The average is then calculated by dividing the sum by the total number of elements in the list.

python

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]))

csharp

The average is 18.4


👉Method 2: Using sum() and len()

This is the simplest and most concise method to calculate the average in Python. The sum() function calculates the total sum of the list, and len() returns the count of elements.

python

number_list = [45, 34, 10, 36, 12, 6, 80]

avg = sum(number_list) / len(number_list)

print(“The average is”, round(avg, 2))

csharp

The average is 31.86


👉Method 3: Using statistics.mean()

The statistics module’s mean() function simplifies the process of calculating the average.

python

from statistics import mean

number_list = [45, 34, 10, 36, 12, 6, 80]

avg = mean(number_list)

print(“The average is”, round(avg, 2))

csharp

The average is 31.86


👉Method 4: Using numpy.mean()

The numpy library provides powerful mathematical functions, including mean() for calculating the average efficiently.

python

from numpy import mean

number_list = [45, 34, 10, 36, 12, 6, 80]

avg = mean(number_list)

print(“The average is”, round(avg, 2))

csharp

The average is 31.86


👉How to Calculate Average of List in Python Summary

Calculating the average in Python can be done in multiple ways: ✅ Using a Loop
✅ Using sum() and len()
✅ Using statistics.mean()
✅ Using numpy.mean()

How to Calculate Average of List in Python

Download Python

Leave a Comment

Index