Median - Why does this code works?


Lets say numbers = [2,5,8,9,200],
Then len(numbers) = 5 therefor len(numbers)/2 = 2.5. Since Python rounds down we get 2.
So if i call numbers[len(numbers)/2] it will give me numbers[2] which is the 3rd item in the list.

how come in this code it gives me the median of the 2 middle ints?

def median(numbers):
    if len(numbers)==1:
        return numbers[0]
    if len(numbers) % 2 != 0:
        return numbers[len(numbers)/2]
        return (numbers[len(numbers)/2] + numbers[len(numbers)/2 - 1]) / 2.0

print median([1,22,9,4,246])


Well, you yourself explained the whole logic of the above code in your post :confused: Are you asking about the case when the list is of even numbered length, like [1, 2, 3, 4]?


never mind I just didnt understand what median is..
after a closer look i got it thanks :slight_smile: