# Median function returns different values for python2.7 and python3

#1

Given a list of [4, 4, 5, 5] the function below returns 4 (wrong answer) as median on python2.7 and returns 4.5 (correct answer) on python3

The code should return 4.5 on both python2.7 and python3. I was testing the code on my laptop using jupyter notebook with python3 where it was working ok (returning 4.5) but when I copy paste the same code to codecademy, it returns 4. Why would this be the case??

``````def median(numbers):
sorted_list = sorted(numbers)
list_len = len(numbers)
last_index = list_len - 1

if list_len % 2 == 0:
middle_index1 = int(last_index / 2)
middle_index2 = middle_index1 + 1
return (sorted_list[middle_index1] + sorted_list[middle_index2]) / 2
else:
middle_index = int(last_index / 2)
return sorted_list[middle_index]

median([5,4,4,5])``````

#2

no, python3 is not backward compatible with python2. One of the changes made was division behavior. in python2 dividing two integers returns a integer (if needs be, the number is floored)

in python3, this behavior was changed, dividing two integers will now return a float unless floor division (`//`) is used

Median - code not working
#3

Thank you very much. I did not have this info before and finally I've managed to get it working by casting the denominator to a float

#5