Find Median of List in Python
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 code to demonstrate working of # Median of list # Using loop + "~" operator # initializing list test_list = [4, 5, 8, 9, 10, 17] # printing list print("The original list : " + str(test_list)) # Median of list # Using loop + "~" operator test_list.sort() mid = len(test_list) // 2res = (test_list[mid] + test_list[~mid]) / 2 # Printing result print("Median of list is : " + str(res)) |
The original list : [4, 5, 8, 9, 10, 17] Median of list is : 8.5
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 code to demonstrate working of # Median of list # Using statistics.median() import statistics # initializing list test_list = [4, 5, 8, 9, 10, 17] # printing list print("The original list : " + str(test_list)) # Median of list # Using statistics.median() res = statistics.median(test_list) # Printing result print("Median of list is : " + str(res)) |
The original list : [4, 5, 8, 9, 10, 17] Median of list is : 8.5
Recommended Posts:
- Python | Find maximum length sub-list in a nested list
- numpy.median() in Python
- Python statistics | median()
- Find average of a list in python
- Find size of a list in Python
- Python | Find all triplets in a list with given sum
- Python | Find Min/Max in heterogeneous list
- Python | Pandas Series.median()
- Python | Pandas dataframe.median()
- Python | Ways to find indices of value in list
- Python | Find most common element in a 2D list
- Python | Find most frequent element in a list
- Python | Ways to find length of list
- Python | Find Mean of a List of Numpy Array
- Python | Find indices with None values in given list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



