15/15 Median (List index out of range)


Hey guys having a little trouble with my program here. I figured that it has something to do with my if and else statements, but I can't figure out how to correct it:

def median(num):
    sorts = sorted(num)
    x = len(num)
    location = int(x/2)
    if x % 2 == 0:
        mid = (sorts[x] + sorts[x - 1])/(2.0)
         return mid
        mid = (sorts[x])
        return mid

I tried making this change, but it still came up with the same problem:

if x % 2 == 0 and len(sorts) > 1:

Any help would much be appreciated. Thanks in advance!


What does it fail on?


It fails on line 6. I get this message:

Traceback (most recent call last):
  File "python", line 11, in <module>
  File "python", line 6, in median
IndexError: list index out of range


Well, okay, so you have a line number, go check out what accessing by index you do there.
Use a print statement to print out both the index(es) that you're accessing, and the list itself. Does that index exist?

print x, sorts


>>> median([1, 2])
2 [1, 2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "delme.py", line 7, in median
    mid = (sorts[x] + sorts[x - 1])/(2.0)
IndexError: list index out of range

Our print there is:

2 [1, 2]

You use 2 as the index for a list that has a length of 2, the highest valid index for such a list is 1 (first index is 0, second index is 1)


Oh I get it. So I was calling on the full length of the list instead of the location of the median. After looking through my program I realized I was calling on "x" instead of "location." After switching "x" with "location" it worked perfectly.

Thank you so much for the help!