This post will discuss how to calculate the average of all elements in a Python List.

There are several methods to find the average of all items in a Python listt:

1. Using sum() and len() functions

The preferred, fast way to get the average of a sequence of integers is to use the sum() and len() functions. These functions are built-in functions in Python that return the sum and length of an iterable respectively. We can calculate the average by the division of the total sum with the length of the list. The result will be a float value representing the average of all items in the list. Here is an example of how to use this method:

Download  Run Code

 
This method works for any type or size of a list. To get floating-point values with extended precision, consider using the math.fsum() function.

Download  Run Code

2. Using reduce() and lambda functions

Another way to compute the average is to use the reduce() functions with lambda expression. The reduce() function applies a given function to the elements of an iterable and returns a single value. We can use it to calculate the sum of all items in a list and then divide it by the length of the list. For example:

Download  Run Code

3. Using statistics.mean() function

The statistics module provides several functions for calculating mathematical statistics of numeric data. We can use the statistics.mean() function to get the arithmetic mean of an iterable having numeric values. The result will be a float value representing the average of all items in the list. Here is an example of using this method:

Download  Run Code

4. Using numpy.mean() function

A final way to find the average of all items in a Python list is to use the numpy.mean() function from the numpy module, which computes and returns the arithmetic mean of an array or an iterable having numeric values. It returns a floating-point value representing the average of all items in the list. Here is an example of its usage:

Download Code

That’s all about finding the average of all items in a list in Python.