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. 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

2. 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