Median - list index out of range


#1

<Below this line, add a link to the EXACT exercise that you are stuck at.>
https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/median?action=lesson_resume

I receive an error message for the test for an even list.
“median([4, 5, 5, 4]) resulted in an error: list index out of range”

I’m not messing with the index, and I think I’m dealing with the length correctly.
Can anyone help me spot my error(s)?



def median(nos):
  median = 0
  foo = len(nos) 
  bar = sorted(nos)
  
# solve for even list  
  if foo % 2 == 0:
    a = bar[foo / 2] # a = value right of mid
    b = bar[a - 1] # b=value left of mid
    median == (a + b) / 2.0 # average l+r

  elif foo == 1: #if the list is 1 item
    median = bar[0]

  else: # solve for odd list
    median = [round(foo / 2)] # center value
    
  return median


#2

Set this to an assignment.


#3

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