Range and IQR
Descriptive Statistics
The Simplest Measures of How Spread Out Your Data Is
Measures of spread tell us how scattered the data is. Range and IQR are the simplest measures — they use only specific order statistics.
- Range — The difference between max and min; simple but brutally sensitive to outliers
- IQR — The middle 50% of data; robust and reliable for skewed distributions
- Outlier detection — The 1.5 times IQR rule flags suspicious values automatically
- Box plot foundation — The IQR forms the box in every box plot you will ever make
Spread matters as much as center. Two datasets with the same mean can behave very differently.
What You'll Learn
- 1Compute the range and interquartile range from raw data and the five-number summary
- 2Explain why the range collapses under a single outlier while the IQR does not
- 3Reproduce quartile values under competing interpolation conventions
- 4Apply the 1.5 times IQR fence rule and read what a flagged point means
What are Range and IQR?
Definition
Measures of spread (dispersion) tell us how scattered the data is. Range and IQR are the simplest measures — they use only specific order statistics.
A measure built only from order statistics depends on rank, not on distance from the mean, which is exactly why the IQR survives contamination that destroys the standard deviation. The range needs only two numbers, the largest and the smallest, so it is cheap to compute and easy to explain, but those two numbers are precisely the ones an outlier controls.
Range
Simple but highly sensitive to outliers — one extreme value changes it completely.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
np.random.seed(42)
data = np.array([12, 15, 14, 10, 18, 20, 16, 11, 13, 17])
data_with_outlier = np.append(data, 100)
print(f"Data: {sorted(data)}")
print(f"Range = {data.max()} - {data.min()} = {data.max() - data.min()}")
print(f"\nWith outlier (100 added):")
print(f"Range = {data_with_outlier.max()} - {data_with_outlier.min()} = {data_with_outlier.max() - data_with_outlier.min()}")
print("Range nearly quadrupled due to one outlier!")
The range also carries an inconvenient statistical property: as a statistic of a sample it never estimates the population range well, because new observations almost always extend it. Its legitimate uses are narrow — confirming the measurement scale, checking that values fall inside a plausible interval, and monitoring a process where the extremes themselves are the quantity of interest.
Interquartile Range (IQR)
The range of the middle 50% of the data. Robust to outliers.
# Computing quartiles and IQR
def five_number_summary(data):
q1, q2, q3 = np.percentile(data, [25, 50, 75])
iqr = q3 - q1
lower_fence = q1 - 1.5 * iqr
upper_fence = q3 + 1.5 * iqr
print(f"Min: {data.min():.2f}")
print(f"Q1: {q1:.2f}")
print(f"Median: {q2:.2f}")
print(f"Q3: {q3:.2f}")
print(f"Max: {data.max():.2f}")
print(f"IQR: {iqr:.2f}")
print(f"Lower fence (Q1 - 1.5x IQR): {lower_fence:.2f}")
print(f"Upper fence (Q3 + 1.5x IQR): {upper_fence:.2f}")
return q1, q2, q3, iqr
print("=== Normal data ===")
five_number_summary(data)
print("\n=== Data with outlier ===")
five_number_summary(data_with_outlier)
print("IQR barely changed — robust!")
How the Quartiles Get Computed
There is no single universally agreed definition of a quartile, and software quietly disagrees. The methods split into two families: exclusive methods remove the median from the halves before taking their medians (the approach many textbooks and Tukey's original box plot use), while inclusive methods keep the median in both halves. When the median falls on an observed value the two families return different answers, and interpolation between order statistics adds a third layer of variation.
| Method | Where you meet it | Q1 for 10,11,12,13,14,15,16,17,18,20 | IQR |
|---|---|---|---|
| Tukey hinges (exclusive) | Textbooks, TI calculators, some box plots | 12 | 5 |
| Linear interpolation (type 7) | NumPy, pandas, R default | 12.25 | 4.5 |
| Averaging (type 6) | SAS default, older spreadsheets | 12.5 | 4.25 |
| Nearest rank | Reporting percentiles without interpolation | 13 | 4 |
data = np.array([10, 11, 12, 13, 14, 15, 16, 17, 18, 20])
print("Q1:", np.percentile(data, 25), "| default is linear (type 7)")
print("Q1 (lower):", np.percentile(data, 25, method='lower'))
print("Q1 (higher):", np.percentile(data, 25, method='higher'))
print("Q1 (nearest):", np.percentile(data, 25, method='nearest'))
print("pandas quantile:", pd.Series(data).quantile(0.25))
# Tukey hinges: medians of the lower and upper halves, median excluded
lower_half = data[:len(data)//2]
upper_half = data[len(data)//2:]
print(f"Tukey hinges: Q1={np.median(lower_half)}, Q3={np.median(upper_half)}")
print(f"IQR: exclusive={np.median(upper_half) - np.median(lower_half)}, "
f"linear={np.percentile(data, 75) - np.percentile(data, 25)}")
Whichever convention you pick, use it consistently inside one analysis. Mixing a hand-computed quartile with a library fence, or comparing two dashboards built on different defaults, produces disagreements that look like data problems but are really definition problems.
Worked Example: Five-Number Summary by Hand
The factor 1.349 is not arbitrary: for an exactly normal distribution the distance from the 25th to the 75th percentile is 1.349 standard deviations, so dividing the IQR by it recovers an estimate of spread that ignores the tails entirely.
Reading Spread: Rules of Thumb
- A range with no context is meaningless. Always state the unit and the sample size, because a range of 12 tells you far less at than at .
- IQR compared with the range tells you about tail weight. When IQR is more than a third of the range, the middle is dense and the extremes are isolated; when the ratio approaches one, the data is nearly uniform.
- IQR equal to zero means at least half the observations share one value. That is common in rating scales, counts of small integers, and heavily rounded measurements — and it makes the fence rule degenerate, since both fences collapse onto that value.
- Report the IQR next to the median for skewed data, and the standard deviation next to the mean only for symmetric, outlier-free data. Pairing a median with a standard deviation mixes two incompatible views of the distribution.
- Coefficient of variation normalizes spread by the mean, but only makes sense on ratio-scale data with a meaningful zero.
Visualizing Range and IQR
# Two datasets with same mean and range but different IQR
np.random.seed(0)
dataset_a = np.random.uniform(0, 100, 200) # Uniform: large IQR
dataset_b = np.random.normal(50, 10, 200) # Normal: smaller IQR
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
for ax, data, label, color in zip(axes,
[dataset_a, dataset_b],
['Uniform', 'Normal'],
['steelblue', 'coral']):
ax.hist(data, bins=30, color=color, edgecolor='black', alpha=0.7, density=True)
q1, q2, q3 = np.percentile(data, [25, 50, 75])
ax.axvline(data.min(), color='gray', linestyle=':', label=f'Min={data.min():.0f}')
ax.axvline(q1, color='blue', linestyle='--', label=f'Q1={q1:.0f}')
ax.axvline(q2, color='red', linestyle='-', linewidth=2, label=f'Median={q2:.0f}')
ax.axvline(q3, color='blue', linestyle='--', label=f'Q3={q3:.0f}')
ax.axvline(data.max(), color='gray', linestyle=':', label=f'Max={data.max():.0f}')
ax.fill_betweenx([0, ax.get_ylim()[1] if ax.get_ylim()[1] > 0 else 0.05],
q1, q3, alpha=0.2, color='yellow', label=f'IQR={q3-q1:.0f}')
ax.set_title(f'{label} Distribution\nRange={data.max()-data.min():.0f}, IQR={q3-q1:.0f}')
ax.legend(fontsize=7)
plt.tight_layout()
plt.savefig('range_iqr.png', dpi=150)
plt.show()
The uniform sample spreads its middle 50% across nearly half the full range, while the normal sample concentrates it: same nominal range, very different IQR. That contrast is the fastest visual way to see that the range says nothing about where the typical observation lives.
Comparing Spread Measures
| Measure | Formula | Breakdown Point | Sensitive To |
|---|---|---|---|
| Range | Max - Min | 0% | Very sensitive to outliers |
| IQR | Q3 - Q1 | 25% | Robust |
| Std Dev | √(Σ(xᵢ-x̄)²/(n-1)) | 0% | Sensitive to outliers |
| MAD | Median(|xᵢ - Median|) | 50% | Very robust |
The breakdown point is the share of contaminated observations a statistic tolerates before it can be ruined. The range and the standard deviation fail the moment one observation is corrupt; the IQR tolerates contamination of the lower or upper quarter because those points never enter or ; the median absolute deviation tolerates half. In practice the IQR is the default for exploratory work because it is robust while still using more of the data than the median alone.
Range and IQR in Machine Learning
| ML Application | Range/IQR Usage | Why |
|---|---|---|
| Outlier detection | IQR fence = Q1-1.5×IQR to Q3+1.5×IQR | Robust to skewed data |
| Feature selection | Zero/near-zero range → remove feature | No information content |
| Min-Max normalization | Scale to [0,1] using range | Neural networks need bounded inputs |
| Box plots | IQR defines the box | Visual model diagnostics |
| Anomaly detection | IQR-based thresholds | Production data monitoring |
import numpy as np
from sklearn.preprocessing import MinMaxScaler
np.random.seed(42)
# IQR-based outlier detection
data = np.concatenate([np.random.normal(50, 10, 100), [200, -50]])
q1, q3 = np.percentile(data, [25, 75])
iqr = q3 - q1
lower, upper = q1 - 1.5*iqr, q3 + 1.5*iqr
outliers = data[(data < lower) | (data > upper)]
print(f"IQR: {iqr:.2f}, Fences: [{lower:.2f}, {upper:.2f}]")
print(f"Outliers detected: {len(outliers)} ({outliers})")
# Min-Max normalization using range
data_features = np.random.randn(100, 3) * [10, 1, 100] # very different ranges
scaler = MinMaxScaler()
normalized = scaler.fit_transform(data_features)
print(f"\nOriginal ranges: {[f'{d.max()-d.min():.1f}' for d in data_features.T]}")
print(f"Normalized ranges: {[f'{d.max()-d.min():.3f}' for d in normalized.T]}")
Min-max scaling exposes the range's other weakness: a single extreme value compresses every normal observation into a narrow band near the middle of the interval. When a feature has known bounds — a percentage, an age, a count with a documented maximum — clip to those bounds first; when it does not, robust scaling built on quartiles is usually the safer transformation.
Frequently Asked Questions
Which is better, range or standard deviation?
Neither is universally better; they answer different questions. The range is a quick bound on where values sit and is the right tool when the extremes matter, while the standard deviation describes typical distance from the mean and feeds most inferential formulas. For skewed or contaminated data, prefer the IQR over both.
Why does the box plot rule use 1.5 and not 1 or 2?
Under an exactly normal distribution, 1.5 times the IQR reaches about 2.7 standard deviations, which flags roughly one observation in 300 as an outlier — frequent enough to be useful, rare enough to stay informative. Smaller multipliers flood the plot with points, larger ones hide genuine anomalies.
Can the IQR be zero?
Yes. If at least half the observations are identical, and coincide. Ratings, integer counts and rounded measurements do this constantly, and it also makes the fence rule flag every value that differs from the majority, so treat such flags as a property of the scale rather than as data errors.
Common Mistakes
Quoting the range as a summary of spread for data with outliers
Fix: Report the IQR alongside the median; keep the range only as a bound with the unit stated.
Comparing quartiles computed by different software
Fix: Pick one interpolation convention and record it, since exclusive and linear methods disagree on small samples.
Deleting every point the 1.5×IQR rule flags
Fix: Investigate first: a flagged point may be a measurement error or the most interesting observation in the dataset.
Interview Questions
Q1: Why is the IQR preferred over the standard deviation for house prices?
House prices are right-skewed with multi-million dollar outliers. The standard deviation uses every squared deviation, so a few mansions dominate it, while the IQR only reads the 25th and 75th percentiles of the bulk of the market.
Q2: What does an IQR of zero tell you?
At least half the values are identical. On a rating scale or small integer counts that is normal, and it also makes the fence rule degenerate, so flags should be interpreted against the scale, not as errors.
Q3: How do you estimate the standard deviation without the standard deviation?
Divide the IQR by 1.349. That constant is the normal-theory distance between the first and third quartiles, so the estimate is reliable for roughly normal data and deliberately blind to the tails.
Q4: When would you report the range at all?
When the extremes are the quantity of interest — control charts, plausibility checks on measurement scales, or a quick bound with the unit and sample size attached.
Key Takeaways
Key Takeaways
- Range is max minus min: cheap, intuitive, and destroyed by a single extreme value
- IQR is the span of the middle 50%, robust because contamination sits outside Q1 and Q3 entirely
- The 1.5×IQR fences define outliers for box plots, and the multiplier is calibrated to normal data, about 2.7 standard deviations
- Quartiles have competing definitions — exclusive, inclusive and interpolated — so fix one convention before comparing numbers
- Dividing the IQR by 1.349 estimates the standard deviation of normal data without ever touching the tails