Find average of numbers in a list using python

Calculate the average of numbers in a list using python :

In this tutorial, we are going to show you three different ways to calculate average of numbers of a list in python.We are using python3 version 3.6.1 . You can check your python3 version by running python3 –version command on a terminal.
1. We will get the inputs from the user
2. Input numbers should be entered with comma (‘,’) as a separator
3. We will create one list from the inputs .
4. To create the list, first input numbers will be splited by ‘,’ using split() method. split() returnes a list of strings of all the numbers . we will convert it all to integer using int(string) method.
5. Finally to find the average , divide the summ of all numbers by length of the list. The sum of all elements in a list is sum(list_name) and lenght of a list is len(list_name). Following is the complete program :

1. Normal method :

numberList = []
print ("Enter all numbers with ',' as separator")
numberList = [int(i) for i in input().split(',')]
print ("Average = ",sum(numberList)/len(numberList))

2. Using ‘statistics’ module :

statistics module contains mathematical statistics functions like mean, median, harmonic mean etc. We will use this module to find out the average or mean of all numbers .

from statistics import mean
numberList = []
print ("Enter all numbers with ',' as separator")
numberList = [int(i) for i in input().split(',')]
print ("Average = ",mean(numberList))

3. Using reduce :

reduce is a very useful function to work with list elements without iterating it with a loop. We can pass a lambda or rule to it and it will return the final result by doing a rolling computation on the list value. Here , we will pass one lampda x,y : x+y to reduce with the element list as argumet. It will calculate the sum of all elements of the list using the above lambda. ‘reduce’ is in ‘functools’ module.

from functools import reduce
numberList = []
print ("Enter all numbers with ',' as separator")
numberList = [int(i) for i in input().split(',')]
print ("Average = ",reduce(lambda x,y:x+y, numberList)/len(numberList))

Sample input :

Enter all numbers with ',' as separator
1,2,3,4,5,6
Average = 3.5 //using method 1
Average = 3.5 //using method 2
Average = 3.5 //using method 3

If you know any other ways to calculate the average or if you have any doubt, please leave a comment below.

Leave a Reply