In this program, we will get the median of all the elements from the list.
Steps to solve the program
- Take an input list with some values.
- Sort list items with the sorted() function.
- Get the length of the sorted list.
- If the length of the list is an even number then the median of the list will average two mid-values of the list.
- 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
- Python program to print a combination of 2 elements from the list whose sum is 10.
- Python program to print squares of all even numbers in a list.
- Python program to split the list into two-part, the left side all odd values and the right side all even values.
- Python program to get common elements from two lists.
- Python program to reverse a list with for loop.
- Python program to reverse a list with a while loop.