# Find median of [2, 5, 2, 6, 7, 3, 7, 5, 7, 0, 6, 10]

Ok, I'm encountering this weird result when performing:

l = [2, 5, 2, 6, 7, 3, 7, 5, 7, 0, 6, 10]
r = median(l)


The r becomes 11/2 which is 5.5. The median here is clearly an integer and it is 5!

Why does it return 5.5?

edit retag close merge delete

The list has length 12 (even). I think what sage is returning is the average of elements at positions 6 and 7, which are 5 and 6.

Sort by » oldest newest most voted
if hasattr(v, 'median'): return v.median()

if len(v) == 0:
# Median of empty set defined as NaN
return NaN
values = sorted(v)
if len(values) % 2 == 1:
return values[((len(values))+1)/2-1]
else:
lower = values[(len(values)+1)/2-1]
upper = values[len(values)/2]
return (lower + upper)/ZZ(2)

more

For completeness: "If there is an even number of observations, then there is no single middle value; the median is then usually defined to be the mean of the two middle values..." see https://en.wikipedia.org/wiki/Median

How do you guys read the answer? I don't understand this. I am new to this website.

more

See the comment under the answer - I posted the code itself but the comment is probably easier to get!