CBSE Class 11 Informatics Practices
Question 57 of 80
Lists in Python — Question 20
Back to all questions 20
Question 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.
n = int(input("Enter number of elements in the list: "))
nums = []
print("Enter the elements of the list:")
for i in range(n):
n1 = int(input("Enter element: "))
nums.append(n1)
nums.sort()
n = len(nums)
if n % 2 == 0:
mid1 = nums[n // 2 - 1]
mid2 = nums[n // 2]
median = (mid1 + mid2) / 2
else:
median = nums[n // 2]
print("Median of the list is:", median)Enter number of elements in the list: 6
Enter the elements of the list:
Enter element: 10
Enter element: 20
Enter element: 4
Enter element: 45
Enter element: 99
Enter element: 30
Median of the list is: 25.0
Enter number of elements in the list: 5
Enter the elements of the list:
Enter element: 3
Enter element: 7
Enter element: 9
Enter element: 5
Enter element: 11
Median of the list is: 7