Python statistics.mean() Function

Python statistics.mean() method is used to calculate the mean/average of a given list of numbers.

To use the mean() method, you need to import the statistics module.

Syntax

mean(data)

Parameters

data: List or tuple of a set of numbers.

Return value

It is a sample arithmetic mean of the provided data set.

Exceptions

TypeError occurs when anything other than numeric values is passed as a parameter.

Example 1: Calculating the mean of a list

Visual representation of Calculating the mean of a list

import statistics

main_list = [1, 1, 2, 2, 3]

mean_of_list = statistics.mean(main_list)

print(mean_of_list)

Output

1.8

Example 2: Calculating the mean of the dictionary

Visual representation of Calculating the mean of the dictionary

import statistics

main_dict = {1: 19, 1:21, 2:18, 2:46, 3:30}

mean_of_dict = statistics.mean(main_dict)

print(mean_of_dict)

Output

2

Example 3: Calculating a mean of a tuple of a negative set of integers

Visual representation of Calculating a mean of a tuple of a negative set of integers

import statistics

negative_set = (-11, -21, -18, -19, -46)

mean_of_negative_set = statistics.mean(negative_set)

print(mean_of_negative_set)

Output

-23 

Let’s take an example of the tuple of a mixed range of numbers.

Visual representation of calculating mean of mixed integers set

import statistics

mixed_set = (11, 21, -18, 19, -46)

print(statistics.mean(mixed_set))

Output

-2.6

Example 4: Calculating the mean of a list of a negative set of integers

Visual representation of Calculating the mean of a list of a negative set of integers

import statistics

negative_list = [-11, -21, -18, -19, -46]

mean_of_negative_list = statistics.mean(negative_list)

print(mean_of_negative_list)

Output

-23

Let’s take an example of the list of a mixed range of numbers.

Visual representation of calculating mean of mixed list

import statistics

mixed_list = [11, 21, -18, -19, 46]

print(statistics.mean(mixed_list))

Output

8.2

Example 5: TypeError: can’t convert type ‘str’ to numerator/denominator

TypeError - can't convert type 'str' to numerator:denominator

import statistics

data = {"a": 11, "b": 21, "c": 19, "d": 29, "e": 18}

print(statistics.mean(data))

Output

TypeError: can't convert type 'str' to numerator/denominator

We got the TypeError because statistics.mean() expects an iterable of numbers, and we passed an entire dictionary data instead of just its values.

The correct approach is to extract the values from the dictionary using dict.values() function and then calculate the mean.

import statistics

data = {"a": 11, "b": 21, "c": 19, "d": 29, "e": 18}

# Extract the values from the dictionary and calculate the mean
mean_value = statistics.mean(data.values())

print(mean_value)

Output

19.6

That’s all!

2 thoughts on “Python statistics.mean() Function”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.