In the previous article, we explored the concept of Comprehensions in Python. Now let us look at how we can obtain the average or mean of a list in Python. Let us look at an example, we have a list l1:
There are four elements in the list, and the average can be obtained by dividing the sum of all the elements by the number of elements in total. Hence the result should be 25. Suppose we had a different list, l2:
There are three elements in the list and the sum is 130. When we divide 130 by the number of elements we obtain 43.33. Finding out the average or mean of a list of values can have multiple real life applications such as automatically calculating the average marks scored by the students for an exam, or imagine a scenario where we need to find out how much time a user spends on a certain application in average.
Program to determine Average or Mean of a List in Python
Let us write a function to process a list’s elements and then return the average, utilizing the same logic as discussed earlier.
def average(l): sum=0 for x in l: sum=sum+x n=len(l) return sum/n l=[10,20,30,40] print(average(l))
The function first finds the sum of all the elements(it is initialized as zero) ,traverses through a loop for every item in the list and adds them together to obtain the required sum. Once the sum is obtained it is divided by the number of elements present in the list( which is determined by using the len( ) built-in function).
We can also solve using sum( ) & and len( ) built-in functions, alternatively:
def average(l): return sum(l)/len(l) l=[10,20,30,40] print(average(l))
Thus, we have seen how we can obtain the average or mean of a list in Python. In the next article we will see how we can count the distinct unique elements of a list.