Search code examples
pythonlistmedian

Median in a list of n elements


I'm trying to determine the median of a list of n elements and I just can't see what I am doing wrong.

I have sorted(list) so that the elements are in the right order but I get a median of 5.0 instead of the correct 4.5.

My code looks like this.

def median(lista):
    median_even1 = 0
    median_even2 = 0
    median_sum = 0
    median_average = 0
    if len(lista) % 2 == 0:
        sorted(lista)
        median_even1 += lista[(len(lista)/2)]
        median_even2 += lista[(len(lista)/2 - 1)]
        median_sum = median_even1 + median_even2
        median_average = (median_sum) // (2.0)
        return median_average
    else:
        sorted(lista)
        return lista[(len(lista) / 2)]

Any suggestions?


Solution

  • sorted() isn't in place, it returns a new sorted list. Either reassign it (lista = sorted(lista)) or use list.sort() instead (lista.sort()).