Median Help


Ok I'm stuck after if statement. I want to know how can i get the 2 median number of the list in the if statement that i've made. Do i use indexing?

def median(lst_middle):
    lst_middle = sorted(lst_middle)
    middle = float(len(lst_middle))
    if middle % 2 == 0:


Have you tried it yet? What is it that you're confused about? The accessing part or getting the middle values?
Also be careful when using the % operator without comparing it to anything. The if statement will always be true.


getting the middle value is what im stuck at. And yes, i forgot to do if middle % 2 == 0:


Ok let's say you have someList = [1, 2, 3, 4] then the middle value would be 2, 3, right? That is somelist[1] and somelist[2]

Let's say we have another otherList = [2, 3, 4, 5, 7, 9, 10, 11] the middle would be 5 and 7 which is otherList[3] and otherList[4]

Do you get the idea? If not then first try to think that the list index starts from 1 instead of 0. Remember that you can think the middle point as half of the numbers.


Right. So if i divide the list in half and -1 will i get 1st middle number?


    if len(lst)==1:
        return lst[0]
    elif len(lst)%2==0:
    return middle

With x equal to len(lst)/2


The code passed without doing that.


I dont understand how the equation work. What does float(lst[x]+lst[x-1] do?


Yes, that's right.

It's the sum of the two middle values. The float is so that if you divide 3 by 2 it will return 1.5 instead of 1.0. But you can also make either the dividend or the divisor a float to achieve the same result e.g. 3/2.0


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