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

The sorted list is [4,4,5,5] and I am retrieving values from the sorted list. What is wrong with my code?

def median(first_list):
    if length%2==0:
        return (second_list[(length/2)-1]+second_list[(length/2)])/2
        return second_list[((length+1)/2)-1]


this is the problem:

print 9 / 2 # 4

this should output 4.5, but python floors (round down) the number if the division uses two integers. Knowing this we can solve the problem by using float


Thanks @stetim94. Solved it using the below code.


This really tripped me up, because I use IDLE as my practice Python shell outside of Codecademy, and this code worked:

def median(loi):
    loi = sorted(loi)
    if len(loi) % 2 == 0:
        a = int(len(loi) / 2)
        b = int(len(loi) / 2 - 1)
        return (loi[a] + loi[b]) / 2
        c = int(len(loi) / 2 - 0.5)
        return loi[c]

Does anyone know why it would work in IDLE, but not in Codecademy? Is it to do with the version of Python, or perhaps there's a setting that doesn't floor integer division that I don't know about?



a change was made in division behavior when python3 was released, dividing an integer by an integer no longer gets floored (round down) in python3


Ah, okay good to know! Same reason I can print without brackets in Codecademy, but need brackets in IDLE. (although I've been training myself to bracket everything after print regardless)

Thank you!!


in python2, print was a statement, in python3 its a function

be careful wit the parentheses/brackets, for example doing this in python2:

print("hello", x)

might cause unintended side effects (given the parentheses cause it to become a tuple (immutable list)


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