Median: list index out of range


What does this error mean? Is it my else formula that is incorrect? I think I'm subtracting 1 from the numbers, not the length. But I can't add (+) two lens together.

def median(list):
    new_list = sorted(list)
    print new_list
    if len(new_list) % 2 == 1:
        m = (new_list[len(new_list) / 2])
        return m
        m = (new_list[len(new_list)] / 2 + (new_list[len(new_list)] / 2) - 1)
        return m


It means your code is attempting to access a list element that does not exist.

There is the error.



    if len(new_list) % 2 == 1:
        m = (new_list[len(new_list) / 2])

you do it right, yet here you do it wrong:

        m = (new_list[len(new_list)] / 2

this will first get the index of len(new_list) which is an index error since lists are zero index based, and len() start counting at one, before dividing the value at index len(new_list) by 2


I'm not quite sure I follow. In the first one, I still have len(new_list), which you said is not okay because new_list starts at 0. I could change the brackets but it len would still be the same.


but you need to do the math first, you need to get the right middle index (length / 2) before retrieving the value

currently, you retrieve the value at length (index error)


The only way that the following subscript can be legitimately used is if an assignment is made that extends the list.

new_list[len(new_list)] = "some value"

When we consider how many times len() is used it makes perfect sense to cache the value in a simple variable.

n = len(new_list)

Likewise, how many times do we need to halve it?

m = int(n / 2)

Now examine your code and see where these can be used to simplify it and make it easier to read and understand.


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