Open In App

Find average of a list in python

Last Updated : 27 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a list of numbers and the task is to find the average (or mean) value of its elements. For example, if we have a list nums = [10, 20, 30, 40], the sum of the elements is 10 + 20 + 30 + 40, which equals 100. The number of elements in the list is 4. So, the average is calculated as 100 / 4, which gives the result 25.0. Let’s now explore different methods to do this efficiently.

Using sum()

The most common way to find the average of a list is by using the built-in sum() function. It’s quick, readable and efficient. Just divide the total of the list elements by the number of elements.

[GFGTABS]
Python

a = [2, 4, 6, 8, 10]

avg = sum(a) / len(a)
print(avg)


[/GFGTABS]

Output

6.0

Explanation:

  • sum(a) calculates the total sum of all the numbers in the list.
  • len(a) returns the count of elements in the list.
  • By dividing the sum by the count (sum(a) / len(a)), we get the average.

Using a Loop

Another common way to find the average is by manually calculating the sum of list elements using a loop (for loop).

[GFGTABS]
Python

a = [2, 4, 6, 8, 10]
total = 0

for val in a:
    total += val

avg = total / len(a)
print(avg)


[/GFGTABS]

Output

6.0

Explanation:

  • We initialize sum to zero.
  • We iterate through the list and add each element to sum.
  • Finally, dividing sum by the number of items (len(a)) to get the average.

Using the Statistics Library

Python’s statistics module has a convenient mean() function, which can be very useful for finding the average while maintaining clean code.

[GFGTABS]
Python

import statistics
a = [2, 4, 6, 8, 10]

avg = statistics.mean(a)
print(avg)


[/GFGTABS]

Output

6

Explanation: We use the mean() function from statistics to directly calculate the average.

Using numpy.average()

numpy.average() function computes the mean of an array and can handle more advanced operations, making it highly useful in numerical and data analysis contexts.

[GFGTABS]
Python

import numpy

a = [2, 4, 6, 8, 10]
avg = numpy.average(a)

print(avg)


[/GFGTABS]

Output

6.0

Explanation: numpy.average() function calculates the mean of the list a.

Related Articles:



Next Article
Practice Tags :

Similar Reads