Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

# What is the statistics.harmonic_mean() function in Python?

Sumit Sharma

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

In this shot, we will discuss how to use the statistics.harmonic_mean() function in Python.

### Introduction

Statistics is a very useful module in Python that provides functions to calculate mathematical statistics of numeric data.

Statistics supports both int and float type numeric data. Some of the functions in the statistics module in Python include:

• mean()
• median()
• mode()
• geometric_mean()
• harmonic_mean()

### Harmonic mean

To calculate the harmonic mean, we first find the sum of the reciprocals of all the observations, and then divide the total number of observations by that sum.

If a list of numbers contains a,b,c, then:

Harmonic mean = $\frac{3}{1/a + 1/b + 1/c}$

For example, let the list of numbers be 1, 4, and 4. Their harmonic mean is:

$\frac{3}{1/a + 1/b + 1/c}$ = $\frac{3}{1.5}$ = 2

### Code

Let’s take a look at the code snippet below.

import statisticsdata = [1, 4, 4]result = statistics.harmonic_mean(data)print(result)
Using the statistics.harmonic_mean() function

### Explanation

• In line 1, we import the statistics module to call harmonic_mean().

• In line 2, we provide a list of data whose harmonic mean needs to be found.

• In line 3, we compute the harmonic mean of the provided numbers.

• In line 4, we print the output that is stored in the result.

Note:

• Module_name.function_name is the syntax for calling any function inside a module.

The statistics.harmonic_mean() function comes in handy when we want to compute the central location of the dataset.

RELATED TAGS

python
communitycreator

CONTRIBUTOR

Sumit Sharma

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring

Learn in-demand tech skills in half the time 