How to Find the Average in Python? The Easiest Way



This short tutorial will teach how to use Python for the average of the list and set and how to use Numpy to find the average of an array – matrix columns and rows.

1. Why is it important to take the average of numbers?

The average of numbers, or mean, is an important measure of central tendency because it provides a single value that summarizes the distribution of the data. This can be useful in many applications, such as:

  1. Understanding the overall pattern of the data: The mean gives a good idea of the typical value of the data, which can be helpful in understanding the overall pattern of the data.
  2. Making comparisons: The mean can be used to make comparisons between different groups of data or between data collected at different times.
  3. Estimating future values: The mean can be used to estimate future values based on past data. For example, the average salary of a group of employees can be used to estimate the salary of new employees.
  4. Estimating the distribution of the data: The mean can provide information about the distribution of the data. For example, if the mean is significantly different from the median (another measure of central tendency), it may indicate that the data is skewed in one direction or another.
  5. Simplifying complex data: The mean can be used to simplify complex data by reducing it to a single value, which can be easier to understand and analyze.

In summary, the average of numbers is important because it provides a concise summary of the distribution of the data, which can be useful for understanding patterns, making comparisons, estimating future values, and simplifying complex data.

2. Average in Python

In Python, you can use the native module statistics and import mean to compute the average (mean) of a list or set as we show below

import statistics

my_list = [1, 2, 3, 4]

list_average = statistics.mean(my_list)

my_set = {1, 2, 3, 4}

set_average = statistics.mean(my_set)

print("The List Average is {}".format(list_average))

print("The Set Average is {}".format(set_average))

which prints

The List Average is 2.5
The Set Average is 2.5

3. Numpy Average of Array – Matrix

In case you need to find the average (mean) for the columns or rows of a matrix, you can use numpy.

import numpy

# create matrix
my_matrix = [[1, 2, 3, 4], [1, 1, 1, 1]]

# axis=1 will find the average for the rows
matrix_rows_average = numpy.mean(my_matrix, axis=1)

# axis=0 will find the average for the columns
matrix_columns_average = numpy.mean(my_matrix, axis=0)

print("The Matrix rows Averages are {}".format(matrix_rows_average))
print("The Matrix Columns Averages are {}".format(matrix_columns_average))

which prints

The Matrix rows Averages are [2.5 1. ]
The Matrix Columns Averages are [1.  1.5 2.  2.5]

More Resources

Here are three of my favorite Python Books in case you want to learn more about it.

Related Posts