When I use this code I always get this error message:
Oops, try again. median([1]) resulted in an error: list index out of range

It's meant to return the median of the numbers in the list, but I'm not sure what's wrong with the code.

def median(lst):
    nlst = sorted(lst)
    if len(nlst) % 2 == 0:
        ind = len(nlst) / 2
        med = float((nlst[ind-1] + nlst[ind])/2)
        ind2 = (len(nlst)+1) / 2
        med = nlst[ind2]
    return med



ind2 = (len(nlst)+1) / 2

why plus one? length divided by 2 gives the middle index for odd lists, if you don't believe me, do the math


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.