Median Value

Median Value

Write a function that returns the median of a list of numbers, using the statistics module.

median_value(nums)

Use statistics.median — don't sort and index into the list by hand.

Examples

median_value([1, 2, 3])        // → 2      (the middle value)
median_value([4, 1, 3, 2])     // → 2.5    (even count: average of the two middle values)
median_value([5, 3, 8, 1, 9])  // → 5

Walkthrough

Thinking it through

import statistics


def median_value(nums):
    return statistics.median(nums)

This is the whole point of using a library function instead of writing it yourself: computing a median correctly means sorting the list, then handling two different cases depending on whether the length is odd (return the single middle element) or even (average the two middle elements). statistics.median already does all of that correctly — including for an unsorted input list like [4, 1, 3, 2], which it sorts internally before finding the middle.

Notice the return type differs depending on the input: for an odd-length list, statistics.median returns the middle element exactly as-is (an int, if your input was all ints) — for [5, 3, 8, 1, 9] sorted as [1, 3, 5, 8, 9], the median is 5. For an even-length list, it averages the two middle values, which typically produces a float[4, 1, 3, 2] sorted is [1, 2, 3, 4], and the average of the middle two (2 and 3) is 2.5.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.