How to Compute Percentile Value from Sorted List in Python
Compute any percentile value from a sorted list using linear interpolation between ranks.
Python code
25 linesdef percentile(sorted_data, percentile_value):
"""Return the value below which `percentile_value`% of data falls."""
if not sorted_data:
raise ValueError("Cannot compute percentile of empty list")
if not 0 <= percentile_value <= 100:
raise ValueError("Percentile must be between 0 and 100")
k = (len(sorted_data) - 1) * (percentile_value / 100.0)
lower = int(k)
upper = lower + 1
if upper >= len(sorted_data):
return sorted_data[lower]
if lower == upper:
return sorted_data[lower]
weight = k - lower
return sorted_data[lower] * (1 - weight) + sorted_data[upper] * weight
if __name__ == "__main__":
data = [12, 15, 18, 21, 24, 29, 33, 40]
for p in [0, 25, 50, 75, 100]:
result = percentile(data, p)
print(f"{p}th percentile: {result}")
Output
0th percentile: 12
25th percentile: 15.0
50th percentile: 22.5
75th percentile: 26.25
100th percentile: 40
How it works
This function implements the linear interpolation method (also called the NIST or Excel PERCENTILE.INC method). The formula k = (n-1) * (p/100) finds a fractional rank position in the sorted list. When k is a whole number, it returns that exact value; otherwise, it interpolates between the lower and upper neighbors at that fractional position. The guard clauses handle edge cases like empty lists and out-of-range percentiles, making the function safe for production use. The main block demonstrates output for common percentiles, showing both exact and interpolated results.
Common mistakes
- Forgetting to validate that the input list is sorted before calling the function
- Using integer division (//) instead of float division (/) when computing `k`, which truncates interpolation
- Failing to handle the edge case where `upper` index goes beyond the list length for 100th percentile
Variations
- Use NumPy: `numpy.percentile(data, p)` when already using scientific libraries
- Implement nearest-rank method by rounding `k` up instead of interpolating
Real-world use cases
- Calculating latency SLOs (e.g., p95, p99) from sorted API response time logs in observability dashboards. (193 chars)
- Analyzing test scores or salary bands where business rules require thresholds like the 75th percentile cutoff. (146 chars)
- Determining performance benchmarks and capacity planning by finding percentiles of resource usage metrics. (163 chars)
Sponsored
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.