Python Practice › Basic Programs › Program 6
Median of given numbers
Write a Python program to find the median of given numbers. The median is the middle value after sorting; for an even count it is the average of the two middle values.
Input
[45, 60, 61, 66, 70, 77, 80]
Output
Median: 66
Approach
- Sort the numbers.
- If the count is odd, take the middle item at index
n // 2. - If it is even, average the two middle items.
Solution 1: by hand
numbers = [45, 60, 61, 66, 70, 77, 80]values = sorted(numbers)n = len(values)mid = n // 2 if n % 2 == 1: median = values[mid]else: median = (values[mid - 1] + values[mid]) / 2 print("Median:", median)Output
Median: 66
Line by line
Line 2
sorted() returns a new sorted list, so the original order is kept.
Line 4
For 7 values, 7 // 2 is 3, which is the index of the 4th (middle) item.
Lines 6-9
An odd count has one middle value; an even count averages the two middle values.
Solution 2: statistics module
import statisticsprint(statistics.median([45, 60, 61, 66, 70, 77, 80]))print(statistics.median([3, 1, 4, 2]))Output
66 2.5
Line by line
Lines 2-3
statistics.median() sorts and handles odd and even counts for you; for [3, 1, 4, 2] it averages 2 and 3.
Learn the concept
New to this topic? Read the lesson, then come back.