Median exercise code not succeeding


Hello all, here's a link to the exercise:

My code (figuring below) fails when attempting to find the median of this list [4,5,4,5]
I get the following error message:

Oops, try again. median([4, 5, 5, 4]) returned 4 instead of 4.5

even though my code seems okay to me: I made sure to put a (-1) when referring to the index of the first list element involved in the calculation of the median which I thought to be the main challenge of the program.

Thanks for the help!

def median(lst):
    new_lst = sorted(lst)
    if len(new_lst) % 2 == 0:
        return ((new_lst[(len(lst) / 2) - 1]) + (new_lst[(len(lst) / 2)])) / 2
    if len(new_lst) % 2 != 0:
        return new_lst[(len(lst)) / 2]


If you divide an integer by an integer in python 2.x you'll get an integer as result. If one of the operands is a float you'll get a float result. Try dividing by 2.0 instead of 2.


Thank you very much for the explanation, not just the answer.
Tried it and it works fine now :slight_smile: