To find the average of a list in Python:

**Sum**up the elements of a list.**Divide**the sum by the length of the list.

For instance, let’s calculate an average of a list of numbers:

grades = [4, 3, 3, 2, 5] average = sum(grades) / len(grades) print(f"The average is {average}")

Output:

The average is 3.4

In case you are interested, there are other ways you can compute the average too. Let’s go through these other common approaches.

## The For Loop Approach

The basic way to calculate the average of a list is by using a loop.

In this approach, you sum up the elements of the list using a for loop. Then you divide the sum by the length of the list.

For example:

grades = [4, 3, 3, 2, 5] sum = 0 for number in grades: sum += number average = sum / len(grades) print(f"The average is {average}")

Output:

The average is 3.4

## Find List Average Using mean() Function

Python has a built-in library called `statistics`

. This library provides basic functionality for mathematics in statistical analysis.

One of the useful functions provided by the `statistics`

library is the `mean()`

function. You can use it to calculate the average for a list.

For example:

from statistics import mean grades = [4, 3, 3, 2, 5] average = mean(grades) print(f"The average is {average}")

Output:

The average is 3.4

## Find Average of a List with NumPy mean() Function

NumPy is a commonly used Python library in data science. It provides you with powerful numerical computing tools and multi-dimensional arrays.

This library has also its own implementation of the mean() function.

To use it, first install NumPy by running the following command in your command line window:

from numpy import mean grades = [4, 3, 3, 2, 5] average = mean(grades) print(f"The average is {average}")

Then import the mean function from the **NumPy** library and use it as follows:

The average is 3.4

## Find Average of a List Using reduce() Function in Python

Python’s `functools`

library has a function called `reduce()`

. You use this function when computing the average of a list by calculating the sum of the list.

Let’s use `reduce()`

to calculate the average of a list:

from functools import reduce grades = [4, 3, 3, 2, 5] average = reduce(lambda x, y: x + y, grades) / len(grades) print(f"The average is {average}")

Output

The average is 3.4

The `reduce()`

function works by applying an operation on two elements of a list. It remembers the result and applies the operation on the next element and the result. It does this to accumulate a result for the whole list.

The operation in this example is the lambda expression `lambda x, y: x + y`

.

This is nothing but a function that takes two arguments `x`

and `y`

and returns the sum.

When we call `reduce()`

on a list using this lambda, we tell it to sum up the numbers of a list.

## Conclusion

Today, you learned five ways to figure out the average of a list in Python.

Thanks for reading. I hope you like it.

Happy coding!