Python program to calculate Median of a integer list

Python program to calculate Median of a integer list

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 : 20

Given 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

Leave a Reply

Your email address will not be published. Required fields are marked *

📢 Need further clarification or have any questions? Let's connect!

Connect 1:1 With Me: Schedule Call


If you have any doubts or would like to discuss anything related to this blog, feel free to reach out to me. I'm here to help! You can schedule a call by clicking on the above given link.
I'm looking forward to hearing from you and assisting you with any inquiries you may have. Your understanding and engagement are important to me!

This will close in 20 seconds