Python Practice › List Programs › Program 100
Median of a list
Write a Python program to get the median of all the elements of a list.
Input
[2, 4, 6, 7, 5, 8, 3, 11]
Output
[2, 3, 4, 5, 6, 7, 8, 11] 5.5 5.5
Approach
- Sort; for an even count average the two middle values.
Solution
import statistics items = [2, 4, 6, 7, 5, 8, 3, 11]s = sorted(items)mid = len(s) // 2median = s[mid] if len(s) % 2 else (s[mid - 1] + s[mid]) / 2print(s, median, statistics.median(items))Output
[2, 3, 4, 5, 6, 7, 8, 11] 5.5 5.5
Line by line
Line 5
Eight values, so the median is the average of the 4th and 5th sorted values, 5 and 6.
Learn the concept
New to this topic? Read the lesson, then come back.