Skip to content
Programming Problems · Q5

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: You can use an built-in function to sort the list

CBSENCERTSubjective· 3mImportance★★★★★est
77% · 20/26 Questions
🔒 Locked · start free trial →

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 →

Median = the middle of the sorted data: sort the list (the hinted built-in), then pick element n//2 if n is odd, or average elements n//2 - 1 and n//2 if n is even.

The idea. The median is defined on ordered values, so sorting is the essential first step — exactly what the hint points at (sort()/sorted()). After sorting, integer arithmetic on indices does the rest: with 0-based indexing, the middle of an odd-length list is index n//2, and an even-length list has its two middles at n//2 - 1 and n//2.

Program:

n = int(input("How many numbers? "))
numbers = []
for i in range(n):
    numbers.append(int(input("Enter number " + str(i + 1) + ": ")))

numbers.sort()                      # built-in sort, ascending
mid = n // 2

if n % 2 == 1:                      # odd count -> single middle value
    median = numbers[mid]
else:                               # even count -> average the two middles
    median = (numbers[mid - 1] + numbers[mid]) / 2

print("Sorted list:", numbers)
print("Median =", median)

Expected output — odd case (n = 5, inputs 21, 3, 45, 8, 19):

Sorted list: [3, 8, 19, 21, 45]
Median = 19

Expected output — even case (n = 4, inputs 10, 40, 20, 30):

Sorted list: [10, 20, 30, 40]
Median = 25.0

Index working:

nmid = n//2odd/evenmedian expressionvalue
52oddnumbers[2]19

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.