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
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
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
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.
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
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.
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
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!
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
many thanks a good deal this website is actually professional and simple
well explained