Open In App

Find Median of List in Python

Last Updated : 12 Jul, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

The median is the middle value in a sorted list. If the list has an odd number of items, it's the center one, if even, it's the average of the two middle values. It's used to find the center of data.

Let's look at the different ways to find the median in Python.

Using statistics.median()

statistics.median() function returns the median of a list. It automatically handles both even and odd-length lists and gives the middle value after sorting the data. It's the easiest way to find the median.

Python
import statistics 
li = [4, 5, 8, 9, 10, 17] 
res = statistics.median(li) 
print(res) 

Output
8.5

Explanation: statistics.median() calculates the middle value of the list automatically.

Using sort()

Sorts the list in ascending order, then finds the middle value based on list length to calculate the median. It's a simple and direct way to find the median.

Python
li = [4, 5, 8, 9, 10, 17]
li.sort()
n = len(li)

if n % 2 == 0:
    res = (li[n//2 - 1] + li[n//2]) / 2
else:
    res = li[n//2]

print(res)

Output
8.5

Explanation:

  • The list li is sorted, then n = len(li) calculates its length.
  • If n is even, (li[n//2 - 1] + li[n//2]) / 2 gives the median; else, li[n//2] is used.

Using ~ operator

Sort the list to find the middle value. The ~ operator helps access elements from the end, which makes it easier to get the correct index for the median.

Python
li = [4, 5, 8, 9, 10, 17] 
li.sort() 
mid = len(li) // 2
res = (li[mid] + li[~mid]) / 2
print(res)

Output
8.5

Explanation:

  • List is sorted first.
  • The middle index is found using mid = len(li) // 2 and ~mid gives the second middle index.
  • Both values are averaged to calculate and print the median.

Using python heapq.nlargest() or heapq.nsmallest()

heapq.nlargest() and heapq.nsmallest() functions help find the largest and smallest elements in a list. It is used to get the middle values needed to calculate the median, especially in sorted or nearly sorted data.

Python
import heapq
li = [4, 5, 8, 9, 10, 17]
mid = len(li) // 2
if len(li) % 2 == 0:
    res = (heapq.nlargest(mid, li)[-1] + heapq.nsmallest(mid, li)[-1]) / 2
else:
    res = heapq.nlargest(mid+1, li)[-1]
print(res)

Output
8.5

Explanation:

  • For even length, gets two middle values using nlargest() and nsmallest(), then averages them.
  • For odd length, picks the middle value using nlargest().

Related Articles:


Practice Tags :

Similar Reads