Program to get the median of list elements

In this program, we will get the median of all the elements from the list.

Steps to solve the program
  1. Take an input list with some values.
  2. Sort list items with the sorted() function.
  3. Get the length of the sorted list.
  4. If the length of the list is an even number then the median of the list will average two mid-values of the list.
  5. If the length of a list is odd then the mid-value of the list will be
    the median value.
				
					input_lst = [4, 45, 23, 21, 22, 12, 2]

# sort all list values
sorted_lst = sorted(input_lst)

# get length of sorted list
n = len(sorted_lst)

if n%2 == 0:
    # get first mid value
    mid1 = sorted_lst[n//2]
    # get second mid value
    mid2 = sorted_lst[n//2 -1]
    # average of mid1 and mid2 will be median value
    median = (mid1 + mid2)/2
    print("Median of given list :", median)
else:
    median = sorted_lst[n//2]
    print("Median of given list :",  median)
				
			

Output :

				
					# input_lst = [4, 45, 23, 21, 22, 12, 2]

Median of given list : 21.5
				
			

Related Articles

Leave a Comment