HELP! Advanced Python Coding Challenge: Lists, Challenge: 5 - Middle Item

I am attempting to solve the python list challenge 5 using my limited understanding and keep getting an error: “TypeError: list indices must be integers or slices, not float”

Here it the code I attempted –

def middle_element(lst):
  num = len(lst)
  if num % 2 != 0:
    return lst[(num + 1) / 2]
  else:
    return lst[num/2] + lst[num/2 + 1] /2

print(middle_element([5, 2, -10, -4, 4, 5]))

The prompt was:
Create a function called middle_element that has one parameter named lst .

If there are an odd number of elements in lst , the function should return the middle element. If there are an even number of elements, the function should return the average of the middle two elements.

Any help explaining my errors would be much appreciated.

1 Like

I got a very good helpful reply from Dima G. yesterday. Basically the key is that you need double forward slashes for integer division (I had no clue!!)

the following code should work (again, i’m just a messenger, Dima G. the real hero)

def middle_element(lst):
  if len(lst) % 2 == 1:
    return lst[len(lst) // 2]
  if len(lst) % 2 == 0:
    return (lst[len(lst) // 2] + lst[len(lst) // 2 - 1]) / 2
1 Like

AMAZING! Thank you for replying and thank Dima G.

So the lesson is that two forward slashes transform a float to an integer, which allows the program to find the corresponding index in the list.

I realized in the code I posted above I had made a few additional mistakes.

def middle_element(lst):
  num = len(lst)
  if num % 2 != 0:
    return lst[(num - 1) / 2] #this should be a minus, not a plus as I originally had thought.
  else:
    return lst[num/2] + lst[num/2 - 1] /2 # this is also a minus, not a plus.

print(middle_element([5, 2, -10, -4, 4, 5]))

My mistake was dividing the length of the list in half to come up with the middle number but then forgetting that the index starts at zero and not one.

No, the // performs integer division (also referred to as floored quotient in the Python docs, since you can technically use it with floats as well).

The numbers here are never floats. len() returns an integer and 2 is an integer. So if len(lst) is 5, then len(lst) // 2 is 2. Because 2 goes into 5 twice (with a remainder of 1). Just wanted to clarify that // doesn’t transform floats to integers. In fact, if you use it with a float you will get a float in return…just floored.

For example:

>>> 3 / 2  # in Python 3, division between int values defaults to a float
1.5

>>> 3 // 2  # Here we get integer division...
1

>>> 3.0 // 2  # ... unless we add a float, in which case it is just rounded down
1.0
3 Likes

ahh thanks for that clarification