Average of list in Python

In this tutorial, we will discuss how we can compute the average of the list in Python.

The average of a list is defined as the sum of elements present in the list divided by the number of elements present in the list.

Here, we will make use of three different approaches to calculate the average of the elements present in the list using Python.

  1. Using sum()
  2. Using reduce()
  3. Using mean()

So, let's get started…

Using sum()

In the first method, we have used the sum() and len() to calculate the average.

The following program illustrates the same-

Output:

The average of the list is  34.5

Explanation-

It's time to have a look at what we have done in the above program-

  1. In the first step, we have created a function that takes a list as its parameter and then returns the average using sum() and len(). We know that sum() is used to calculate the sum of elements and len() tells us about the length of the list.
  2. After this, we have initialized the list whose average, we would like to calculate.
  3. In the next step, we have passed this list as a parameter in our function.
  4. Finally, we printed the resultant value.

In the next program, we will see how reduce() can help us to do the same.

Using reduce()

The program given below shows how it can be done-

Output:

The average of the list is  34.5

Explanation

Let's understand what we have done here-

  1. In the first step, we have imported reduce from functools so that we can use it in our program to compute the average of elements.
  2. Now, we have created a function calc_average that takes a list as its parameter and uses lambda(a precise way of writing functions in python) inside reduce to calculate the average.
  3. After this we have initialized whose average, we would like to calculate.
  4. In the next step, we have passed this list as a parameter in our function.
  5. Finally, we printed the resultant value.

In the last program, we will learn how mean() can be used to calculate the average of list

Using mean()

The following program shows how it can be done-

Output:

The average of the list is  34.5

Explanation-

It's time to have a look at what we have done in the above program-

  1. In the first step, we have imported mean from statistics so that we can use it in our program to compute the average of elements.
  2. Now, we have created a function calc_average that takes a list as its parameter and uses mean() to calculate the average.
  3. After this we have initialized whose average, we would like to calculate.
  4. In the next step, we have passed this list as a parameter in our function.
  5. Finally, we printed the resultant value.

Conclusion

In this tutorial, we learned the different methods of calculating the average of elements present in the list using Python.






Latest Courses