# [solved] median

#1

Hi Ste,

def median(n):
length = len(n)
half_length = length / 2

``````if length % 2 == 0 and length >= 2:
n = sorted(n)
median =  (n[half_length] + n[half_length -1]) / 2.0
elif length == 1:
median = n[length - 1]
else:
median = n[half_length - ]
return median``````

## ERROR MESSAGE:

Oops, try again. median([-1, 2, 6, -5, 4, 2, 9]) returned 6 instead of 2

15. median
#2

Sorry Typo error: Find the code below

``````def median(n):
length = len(n)
half_length = length / 2

if length % 2 == 0 and length >= 2:
n = sorted(n)
median =  (n[half_length] + n[half_length -1]) / 2.0
elif length == 1:
median = n[length - 1]
else:
median = n[half_length - 1]
return median``````

#3

for lists with a odd number of items:

``median = n[half_length - 1]``

why minus -1? half_length perfectly matches the middle index (you can do the math)

#4

I tried as per your suggestion but still getting error. Please look at the error below.

def median(n):
length = len(n)
half_length = length / 2

``````if length % 2 == 0 and length >= 2:
n = sorted(n)
median =  (n[half_length] + n[half_length -1]) / 2.0
elif length == 1:
median = n[length - 1]
else:
median = n[half_length]
return median``````

Oops, try again. median([6, 8, 12, 2, 23]) returned 12 instead of 8

#5

the median is the middle value of a sorted list, is your list sorted when you get the middle value for lists with a odd number of items?

#6