Harmonic Mean in Python – statistics & SciPy (2 Examples)

This page demonstrates how to calculate the harmonic mean in Python programming.

Example Data

x = [1, 4, 7, 3, 5, 7, 1, 2, 8, 4, 1, 7]    # Constructing a list in Python
print(x)                                    # Displaying the example list
# [1, 4, 7, 3, 5, 7, 1, 2, 8, 4, 1, 7]

Example 1: Calculate Harmonic Mean of List Using hmean() Function of SciPy Library

from scipy.stats import hmean
print(hmean(x))                             # Get harmonic mean of list
# 2.3589983618066928

Example 2: Calculate Harmonic Mean of List Using harmonic_mean() Function of statistics Module

import statistics                           # Import statistics
print(statistics.harmonic_mean(x))          # Get harmonic mean of list
# 2.358998361806693

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top