Average of a List in Python

In this post, we will see different ways for how to take the average of a list in python. So without wasting any further time. let’s start by discussing the maths definition of average.

Average also known as the arithmetic mean can be defined as the sum of each element of the given list divided by its length.

1. By Using mean() Function

The mean(data) function from the builtin statistics library takes a list of data as an argument and returns its arithmetic mean.

# python program to find the average of a list in python
from statistics import mean 

# input list
data = [10,12,7,8,5,45.3221]

average = mean(data) # find average

print("Average :",average)

#precision Upto 2 decimals

Here is the output of the above code.

Output :

Output of program to find average of a list in python

2. By Using Builtin Sum Function

In this code example, To obtain the average we first used the built-in sum() function to obtain the total of all elements of the list then divide the total by the length of the list.

data = [10,12,7,8,5,45.3221]

a = sum(data) / len(data)
print("Average :",a)

3. By Using Numpy

In the following code, We used the average() function of the external numpy library to obtain the average of the list.

Note: To use numpy you have to install it manually by using pip. Here are the steps :

  • Open cmd/terminal.
  • For windows os: type “pip install numpy”.
  • For Linux/mac os: type “pip3 install numpy”.
# find the average of a list in python by using numpy
import numpy as np

data = [10,12,7,8,5,45.3221]

print("Average :",np.average(data))

4. By Using For-Loop

In the following code snippet, we used the for-loop to obtain the average of a list in python.

The algorithm.

  • We first initialize a result variable and set it to 0.
  • Then we iterate through each element of the list.
  • On each iteration, We add each element to the result.
  • Finally, we print and obtain the average of the list by dividing the result with the number of elements of the list.
data = [10,12,7,8,5,45.3221]

l = len(data) # length of list
s = 0  # result variable

for i in data: # iterage through data
    s+= i # add it to s

average = s/l # obtain the average
print("Average :",average)

That’s wrap for this tutorial.

Leave a Reply