Python Practice › List Programs › Program 100

Median of a list

EasyList Programs · 100 of 100

Write a Python program to get the median of all the elements of a list.

Advertisement
Input
[2, 4, 6, 7, 5, 8, 3, 11]
Output
[2, 3, 4, 5, 6, 7, 8, 11] 5.5 5.5

Approach

  1. Sort; for an even count average the two middle values.

Solution

Python
import statistics items = [2, 4, 6, 7, 5, 8, 3, 11]s = sorted(items)mid = len(s) // 2median = s[mid] if len(s) % 2 else (s[mid - 1] + s[mid]) / 2print(s, median, statistics.median(items))
Output
[2, 3, 4, 5, 6, 7, 8, 11] 5.5 5.5

Line by line

Line 5

Eight values, so the median is the average of the 4th and 5th sorted values, 5 and 6.

Learn the concept

New to this topic? Read the lesson, then come back.

More list programs

← All 100 List Programs

Leave a Comment