Questions about use of int() in middle_element exercise

Hello everyone,

I have a question about why int() is necessary in the middle_element exercise. The instructions are:

" 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."

This is the code that I wrote:

def middle_element(lst):
    if len(lst) % 2 == 0:
        sum = lst[len(lst)/2] + lst[(lst)/2 - 1]
        return sum / 2
    else:
        return lst[(len(lst) - 1) / 2]
print(middle_element([5, 2, -10, -4, 4, 5]))

When I run this code I get the following error:

Traceback (most recent call last):
  File "script.py", line 7, in <module>
    print(middle_element([5, 2, -10, -4, 4, 5]))
  File "script.py", line 3, in middle_element
    sum = lst[len(lst)/2] + lst[(lst)/2 - 1]
TypeError: list indices must be integers or slices, not float

I understand that a list index must be an integer, but what is the scenario in which this code will produce a float? Because the len(lst) is an even number, won’t the len(lst) / 2 always return an integer?

The codeacademy solution uses int() to solve this:

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

I had forgotten about int() when writing my code, but I am not sure why it is it necessary in this case.

Thanks for your help.

A quick check in the terminal will shed light on the matter:

>>> lst = [1,2,3,4]
>>> len(lst)/2
2.0

And since indices can only be integers, lst[2.0] throws an error. (2.0 is a float in programming, or a double).

3 Likes

Oh right - I should have realized that…

Thanks very much for your help!