The Wayback Machine - https://web.archive.org/web/20250408040155/https://www.geeksforgeeks.org/find-average-list-python/
Open In App

Find average of a list in python

Last Updated : 16 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
News Follow

Finding the average of a list is a common task and widely used in data analysis and everyday computations. This article explores several methods to calculate the average, including built-in functions, loops, and the statistics library. Each method is simple and easy to implement.

The most common way to find the average is by using built-in sum() function. Let’s take an example.

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

# Calcuate the sum of list
# and divide it by length of list
avg = sum(a) / len(a)
print(avg)

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.

Let’s see other different methods to find average of a list in python

Using a Loop

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

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

# Initialize total sum to zero
total_sum = 0

# Iterate over each element in list
# and accumulate sum
for val in a:
    total_sum += val

# Calculate average by dividing total sum
# by length of list
avg = total_sum / len(a)

print(avg)

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.

Python
# Import the statistics module
import statistics

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

# Use the mean() function from statistics
# to calculate the average
avg = statistics.mean(a)

print(avg)

Output
6

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

Using numpy.average()

We can find the average of a list in Python by using average() function of NumPy module.

Python
# importing numpy module
import numpy

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

# calculating average
avg = numpy.average(a)

print(avg)

Output
6.0

Related Articles:



Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg