Find Median of List in Python
Last Updated :
12 Apr, 2023
Sometimes, while working with Python list we can have a problem in which we need to find Median of list. This problem is quite common in the mathematical domains and generic calculations. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loop + “~” operator This task can be performed in brute force manner using the combination of above functionalities. In this, we sort the list and the by using the property of “~” operator to perform negation, we access the list from front and rear, performing the required computation required for finding median.
Python3
test_list = [ 4 , 5 , 8 , 9 , 10 , 17 ]
print ( "The original list : " + str (test_list))
test_list.sort()
mid = len (test_list) / / 2
res = (test_list[mid] + test_list[~mid]) / 2
print ( "Median of list is : " + str (res))
|
Output
The original list : [4, 5, 8, 9, 10, 17]
Median of list is : 8.5
Time Complexity: O(n) where n is the number of elements in the list “test_list”. loop + “~” operator performs n number of operations.
Auxiliary Space: O(1), constant extra space is required.
Method #2 : Using statistics.median() This is the most generic method to perform this task. In this we directly use inbuilt function to perform the median of the list.
Python3
import statistics
test_list = [ 4 , 5 , 8 , 9 , 10 , 17 ]
print ( "The original list : " + str (test_list))
res = statistics.median(test_list)
print ( "Median of list is : " + str (res))
|
Output
The original list : [4, 5, 8, 9, 10, 17]
Median of list is : 8.5
Using python heapq.nlargest() or heapq.nsmallest()
Explanation: Using python’s heapq module, we can use the nlargest() or nsmallest() function to find the median of a list of numbers. This method is useful when we are working with large amount of data and we want to find median of large dataset with minimum memory footprint.
Python3
import heapq
test_list = [ 4 , 5 , 8 , 9 , 10 , 17 ]
print ( "The original list : " + str (test_list))
mid = len (test_list) / / 2
if len (test_list) % 2 = = 0 :
res = (heapq.nlargest(mid, test_list)[ - 1 ] + heapq.nsmallest(mid, test_list)[ - 1 ]) / 2
else :
res = heapq.nlargest(mid + 1 , test_list)[ - 1 ]
print ( "Median of list is : " + str (res))
|
Output
The original list : [4, 5, 8, 9, 10, 17]
Median of list is : 8.5
Time complexity: O(n log(k)) where k = len(test_list)/2
Auxiliary Space: O(k) where k = len(test_list)/2
Method : Using sort the list:
Python3
test_list = [ 4 , 5 , 8 , 9 , 10 , 17 ]
print ( "The original list : " + str (test_list))
test_list.sort()
n = len (test_list)
if n % 2 = = 0 :
median = (test_list[n / / 2 - 1 ] + test_list[n / / 2 ]) / 2
else :
median = test_list[n / / 2 ]
print ( "Median of list is : " + str (median))
|
Output
The original list : [4, 5, 8, 9, 10, 17]
Median of list is : 8.5
Time complexity: O(n log n)
Auxiliary Space: O(n)
Share your thoughts in the comments
Please Login to comment...