Programming Problems · Q4
Q.Write a program to read a list of n integers and find their median.
Note: The median value of a list of values is the middle one when they are arranged in order. If there are two middle values then take their average.
Hint: Use an inbuilt function to sort the list.
CBSENCERTSubjective· 3mImportance★★★★★est
80% · 24/30 Questions
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →Sort the list (the hint says use the inbuilt sort()), then: odd count → the middle
element lst[n//2]; even count → the average of the two middle elements
(lst[n//2 - 1] + lst[n//2]) / 2.
The idea
The median is a positional measure — it only makes sense on ordered data, which is why the
first real step is sorting. With n elements (0-indexed):
| n | Middle position(s) | Median |
|---|---|---|
| odd (e.g. 5) | index n//2 = 2 | that single element |
| even (e.g. 6) | indices n//2 - 1 and n//2 = 2 and 3 | average of the two |
Program
# Median of a list of n integers
n = int(input("How many integers? "))
lst = []
for i in range(n):
lst.append(int(input("Enter integer " + str(i + 1) + ": ")))
lst.sort() # inbuilt sort, ascending (as the hint suggests)
mid = n // 2
if n % 2 == 1: # odd count -> single middle element
median = lst[mid]
else: # even count -> average of the two middle ones
median = (lst[mid - 1] + lst[mid]) / 2
print("Sorted list:", lst)
print("Median :", median)
Sample runs
Odd count:
How many integers? 5
Enter integer 1: 7
Enter integer 2: 1
Enter integer 3: 9
Enter integer 4: 3
Enter integer 5: 5
Sorted list: [1, 3, 5, 7, 9]
Median : 5
Even count:
How many integers? 4
Enter integer 1: 8
Enter integer 2: 2 …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.