In this post, we will see the Python program for calculating the median of a given integer list.
Examples:
Given list: [10, 20, 30, 40, 0, 12, 100]
Median of the given data is : 20Given list: [10, 20, 30, 40, 0, 12, 100, 200]
Median of the given data is : 25.0
Now, let’s see the Python code:
# define a user defined function for
# calculating median of a given list
# of integers
def median(integer_list):
# length of given list
length = len(integer_list)
# check for length of the list
# if list is of even length
# then median value find this way
if length % 2 == 0:
n1 = integer_list[ (length // 2) - 1 ]
n2 = integer_list[ length // 2 ]
median_value = (n1 + n2) / 2
# if list is of odd length
else:
median_value = integer_list[ ((length) // 2 )]
# returning the median value
return median_value
# main code
if __name__ == "__main__" :
# input list - odd length
integer_list_1 = [10, 20, 30, 40, 0, 12, 100]
print("Given list is:",
integer_list_1)
# sort the given list of integers
# in ascending order
integer_list_1.sort()
print("Performing sorting in Ascending order:",
integer_list_1)
print ("Median of the given data is :" ,
median(integer_list_1))
# input list - even length
integer_list_2 = [10, 20, 30, 40, 0, 12, 100, 200]
print("\nGiven list is:",
integer_list_2)
# sort the given list of integers
# in ascending order
integer_list_2.sort()
print("Performing sorting in Ascending order:",
integer_list_2)
print ("Median of the given data is :" ,
median(integer_list_2))
Output:
Given list is: [10, 20, 30, 40, 0, 12, 100] Performing sorting in Ascending order: [0, 10, 12, 20, 30, 40, 100] Median of the given data is : 20 Given list is: [10, 20, 30, 40, 0, 12, 100, 200] Performing sorting in Ascending order: [0, 10, 12, 20, 30, 40, 100, 200] Median of the given data is : 25.0