Grrr.... Not sure why it is not working.

def median(x):
    result = 0
    for n in sorted(x):
        if len(x) % 2 == 0:
            result = (x[len(x)/2] + x[len(x)/2 - 1]) / 2.0
            result = x[len(x)/2]
    return result


Hi @aviss ,

See the documentation on the Python sorted function.

After you call the function, you have accessed x. But has x actually been sorted? You can test it by printing it.


I thought I sorted it in line 3 - for n in sorted(x): But it probably does work like this... I introduced a new list (sorted) and the code works now! Thanks! Will read more about sort().


Hi, @aviss,

Also note that you do not need the for loop. That loop visits every index in the list, but to compute the median after the list has been sorted, you only need to access the one or two middle items in the list.


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