Why do I have to include the `/2` in the `int()`?


Middle Item

I am a little embarrassed to say this but I have come back to this challenge every day for a week and still can’t remember the solution the next day. I think my problem is that I don’t understand why in:

sum = lst[int(len(lst)/2)] + lst[int(len(lst)/2) -1]

this line of code, the int() is not only for the len(lst). Why do I also have to include the “/2” in the int… and even further, why NOT include the “-1”? Maybe if I understood the reason, I would be able to rationalize it and remember.

FAQ: Code Challenge: Lists - Middle Item
FAQ: Code Challenge: Lists - Middle Item

In this mockup, think of each [_] as an element in a list.

  [_],    #  m - 1
  [_],    #  m

The length is 8. To find the approximate middle of the list we divide by 2, which gives 4. We know that lists are zero-indexed so this means the fifth element is part of the middle pair (even length lists need two indexes). So if m = len(lst) // 2, then the middle pair is at lst[m - 1] and lst[m].

Note that when the list is even length, the division results in an integer (or integer equivalent), but when the length is odd, the division will result in a float. That is why we need the int() value, since indexes must be integer. Above I use the integer (floor) division operator rather than the int() constructor.

9 / 2     =>  4.5
9 // 2    =>  4

In Python 3, all division returns a float quotient, and since 4.0 is a float, it cannot be used as an index.

8 / 2     =>  4.0
8 // 2    =>  4


I think it was the last part, the fact that all division leads to a float, that got me. I now remember them teaching that in the very beginning! I need to make sure to add it to my notes. Thank you so much for the thorough explanation!