Calculate Quantiles and Percentiles with Python
Calculate and interpret inclusive quartiles for a numeric dataset with an explicit method.
Example check: Worked and guided code samples are checked against CPython 3.13. Practice uses Pyodide 0.29.5 (Python 3.13) in your browser. How we check lessons
Video lesson: Calculate Quantiles and Percentiles with Python
The preview is stored on this site. YouTube loads only when you press Play. Watch on YouTube
Jump to a chapter
Read the video transcript
Select a timestamp to watch that moment on YouTube.
- 00:00
Five recorded scores are ten, twenty, thirty, forty, and fifty. Where is the first quartile? Many people answer twenty, but a call to Python's standard function without a method argument prints fifteen. Before deciding that one of those numbers is wrong, predict which convention the code has actually selected. Quantiles partition an ordered distribution; they do not discover a unique natural boundary written into the data. In this lesson we will keep the same numbers throughout and change only the interpolation rule. That makes the cause of the difference visible. The website exercise asks you to implement one clearly named convention, so you can
- 00:42
explain the output rather than memorizing a mysterious list of decimals. A percentile locates a position in an ordered dataset. Quartiles are the twenty-fifth, fiftieth, and seventy-fifth percentiles, but their numerical values can depend on the interpolation convention. Python's statistics.quantiles provides inclusive and exclusive methods. The inclusive method places the sample minimum and maximum at the ends of the probability range; the exclusive method treats them as observations from a wider population. Neither method is universally correct without a stated context.
- 01:22
For a reproducible classroom summary of these five recorded values, choose inclusive explicitly and label the method alongside the result. The first terminal run calls statistics.quantiles with n equal to four. It produces three cut points, because four intervals have three internal boundaries. The output is fifteen, thirty, forty-five. Our desired classroom report, however, uses the inclusive convention and expects twenty, thirty, forty. This is not an exception or an arithmetic failure; the default method is different from the report's chosen rule. A silent default can become a subtle dashboard bug if a team switches libraries
- 02:03
or copies code without preserving assumptions. Watch the exact call on screen and notice that it names n but does not name a method. That absence is the important diagnostic clue. The default call uses the exclusive method. For ten, twenty, thirty, forty, and fifty, it returns fifteen, thirty, and forty- five. Someone expecting inclusive quartiles twenty, thirty, and forty might call the output a bug, yet the function has followed its documented default. The broken part of our first run is the unstated assumption about the method, not a Python arithmetic error. Inspect the chosen method and compare both outputs on the same data before changing a
- 02:46
dashboard or an assignment answer. The diagnosis run prints both methods with the exact same list. The exclusive result and inclusive result differ at the lower and upper quartiles; the middle cut stays at thirty. The inclusive convention anchors interpolation at the sample endpoints, while the exclusive convention treats the observed extremes differently. We are not selecting a winner for every discipline. We are selecting an explicit policy so that tests, labels, and readers agree. Check the output order carefully: first quartile, second quartile, third quartile.
- 03:26
The second quartile is the median for this sample. If you later ask for percentiles with n equal to one hundred, the returned list contains ninety-nine cuts rather than one hundred observations. Call statistics.quantiles(values, n=4, method='inclusive') when your stated rule is inclusive interpolation. It returns three cut points in order: Q1, Q2, and Q3. The number n is the number of equal- probability intervals, so quartiles use four and percentiles use one hundred. An index into the percentile cut points must be chosen deliberately: the ninetieth percentile is at index eighty-nine in the list of ninety-nine cuts.
- 04:10
Decide how to handle very small samples, nonnumeric values, and missing measurements before reporting a statistic to users. Now the fixed function rejects samples shorter than two and passes method equals inclusive. It returns a tuple, which makes the three- value contract clear for the task checker. On the original five scores, the result is twenty, thirty, forty. The data were not sorted in place and no values were discarded. The standard-library function handles the interpolation, while our wrapper makes the reporting decision visible. A teammate reviewing the function can see the method without looking up a hidden default.
- 04:51
If your project uses exclusive quantiles instead, change the method and the expected output together; never make a report claim that contradicts the code's convention. Inspect the return statement: tuple wraps the list that quantiles produces, so the caller receives exactly three immutable cut points for n equal to four. The length guard runs first and gives the user a purposeful message rather than leaving tiny-input behavior to an implementation detail. The method argument is the core of the fix. Because the data and n remain the same as in the broken run, the change from fifteen to twenty at Q1 is attributable to the convention.
- 05:34
These are interpolated positions, so integer input can legitimately yield floating-point output. A good test asserts the chosen values, while a good chart caption states the inclusive method and the number of observations. The last run uses two values, then tries a single value. Two values can still be interpolated, but they are weak evidence about a population; the point of the example is a function contract, not statistical certainty. Our wrapper raises ValueError for one value, which a caller can handle rather than displaying an overconfident percentile. We also select the ninetieth percentile from ninety-nine cut points using zero-
- 06:15
based index eighty-nine. Pause and check that indexing arithmetic before reusing it. On the lesson page, try an uneven dataset, record the sample size, and compare the methods. Explain in one sentence why two valid conventions can produce different numeric answers. The fixed function rejects fewer than two values and returns a tuple of three inclusive quartiles. With two values, interpolation still produces cut points, but the estimate is based on very little information. The last run verifies a two-value sample and checks that one value triggers an explicit ValueError.
- 06:56
A quartile is not a count of people, nor does it imply a causal threshold. In a real report, include the sample size, the method, the treatment of missing values, and whether ties occur. The learning task asks for an exact function contract, not a universal claim about every statistics package.
Understand the concept
A percentile locates a position in an ordered dataset. Quartiles are the twenty-fifth, fiftieth, and seventy-fifth percentiles, but their numerical values can depend on the interpolation convention. Python's statistics.quantiles provides inclusive and exclusive methods. The inclusive method places the sample minimum and maximum at the ends of the probability range; the exclusive method treats them as observations from a wider population. Neither method is universally correct without a stated context. For a reproducible classroom summary of these five recorded values, choose inclusive explicitly and label the method alongside the result.
The default call uses the exclusive method. For ten, twenty, thirty, forty, and fifty, it returns fifteen, thirty, and forty-five. Someone expecting inclusive quartiles twenty, thirty, and forty might call the output a bug, yet the function has followed its documented default. The broken part of our first run is the unstated assumption about the method, not a Python arithmetic error. Inspect the chosen method and compare both outputs on the same data before changing a dashboard or an assignment answer.
Call statistics.quantiles(values, n=4, method='inclusive') when your stated rule is inclusive interpolation. It returns three cut points in order: Q1, Q2, and Q3. The number n is the number of equal-probability intervals, so quartiles use four and percentiles use one hundred. An index into the percentile cut points must be chosen deliberately: the ninetieth percentile is at index eighty-nine in the list of ninety-nine cuts. Decide how to handle very small samples, nonnumeric values, and missing measurements before reporting a statistic to users.
The fixed function rejects fewer than two values and returns a tuple of three inclusive quartiles. With two values, interpolation still produces cut points, but the estimate is based on very little information. The last run verifies a two-value sample and checks that one value triggers an explicit ValueError. A quartile is not a count of people, nor does it imply a causal threshold. In a real report, include the sample size, the method, the treatment of missing values, and whether ties occur. The learning task asks for an exact function contract, not a universal claim about every statistics package.
- Quantiles divide an ordered distribution
- Inclusive and exclusive methods differ
- n=4 produces three quartile cuts
- Small samples need an explicit policy
See it step by step
Read the code, predict the output, then compare it with the result.
01. Compare two conventions
from statistics import quantiles
values = [10, 20, 30, 40, 50]
print(quantiles(values, n=4, method='exclusive'))
print(quantiles(values, n=4, method='inclusive'))
[15.0, 30.0, 45.0]
[20.0, 30.0, 40.0]The same observations yield different cut points because the interpolation methods answer slightly different questions.
02. Read the median cut
from statistics import quantiles
q1, q2, q3 = quantiles([10, 20, 30, 40, 50], n=4, method='inclusive')
print(q2, q1 < q2 < q3)
30.0 TrueThe middle cut is the median for this sample, and the three values appear in order.
03. Select the ninetieth-percentile cut
from statistics import quantiles
cuts = quantiles([10, 20, 30, 40, 50], n=100, method='inclusive')
print(cuts[89])
46.0The ninety-nine returned cut points use zero-based indexing, so the ninetieth cut is item eighty-nine.
A closer look
Follow the reasoning, inspect each result, then try the suggested changes in the console below.
Name the interpolation convention
A percentile locates a position in an ordered dataset. Quartiles are the twenty-fifth, fiftieth, and seventy-fifth percentiles, but their numerical values can depend on the interpolation convention. Python's statistics.quantiles provides inclusive and exclusive methods. The inclusive method places the sample minimum and maximum at the ends of the probability range; the exclusive method treats them as observations from a wider population. Neither method is universally correct without a stated context. For a reproducible classroom summary of these five recorded values, choose inclusive explicitly and label the method alongside the result.
Run both calls on the same five-element list. Confirm that the input has not changed, then explain why the lower and upper cuts change while the middle cut remains thirty. A disagreement between software packages is often a method disagreement rather than bad arithmetic.
from statistics import quantiles
values = [10, 20, 30, 40, 50]
print(quantiles(values, n=4, method='exclusive'))
print(quantiles(values, n=4, method='inclusive'))
[15.0, 30.0, 45.0]
[20.0, 30.0, 40.0]- Run inclusive and exclusive methods.
- Record the method with the values.
Interpret three quartile cuts
The default call uses the exclusive method. For ten, twenty, thirty, forty, and fifty, it returns fifteen, thirty, and forty-five. Someone expecting inclusive quartiles twenty, thirty, and forty might call the output a bug, yet the function has followed its documented default. The broken part of our first run is the unstated assumption about the method, not a Python arithmetic error. Inspect the chosen method and compare both outputs on the same data before changing a dashboard or an assignment answer.
Unpack the three returned values instead of calling the first value a median. Quantiles gives boundaries between four intervals. Identify which cut corresponds to fifty percent, and do not claim that exactly one quarter of a tiny sample lies below an interpolated number.
from statistics import quantiles
q1, q2, q3 = quantiles([10, 20, 30, 40, 50], n=4, method='inclusive')
print(q2, q1 < q2 < q3)
30.0 True- Unpack Q1, Q2 and Q3.
- Explain what Q2 means.
Check the sample boundary
Call statistics.quantiles(values, n=4, method='inclusive') when your stated rule is inclusive interpolation. It returns three cut points in order: Q1, Q2, and Q3. The number n is the number of equal-probability intervals, so quartiles use four and percentiles use one hundred. An index into the percentile cut points must be chosen deliberately: the ninetieth percentile is at index eighty-nine in the list of ninety-nine cuts. Decide how to handle very small samples, nonnumeric values, and missing measurements before reporting a statistic to users.
One hundred intervals yield ninety-nine cut points. Check the zero-based index before writing a percentile label. Try two observations and then one observation to see why an explicit function policy is useful even when the standard library could return a result.
from statistics import quantiles
cuts = quantiles([10, 20, 30, 40, 50], n=100, method='inclusive')
print(cuts[89])
46.0- Check the percentile index.
- Test the minimum allowed sample size.
Try it in Python
Edit the example and run it. Python starts in your browser the first time you click Run.
Python console
Ready to runNeed input()? Add one value per line
Your output appears here.
Need a hint?
Call quantiles(values, n=4, method='inclusive') after checking length, then convert its list to a tuple.
Complete the task and select Check task to verify your code.
Quick quiz
Three questions. You can change your answers and try again.
Typical mistakes
Everyone meets these errors. See what causes them and how to fix them.
Assuming the default is inclusive
quantiles(values, n=4)quantiles(values, n=4, method='inclusive')What happens: Q1 is 15.0 rather than the expected inclusive 20.0.
State the interpolation convention explicitly when an exact result matters.
Treating a tiny sample as conclusive
report one observation's quartiles as stablereject fewer than two observations and report sample sizeWhat happens: A summary suggests more evidence than the sample contains.
An arithmetic output is not a substitute for context about how much data was observed.