Advanced Python Code Challenges: Lists Exercise # 5

I’m having trouble understanding why the correct code for this exercise functions the way it does and was hoping someone can explain it to me.

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)]

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

I’m having trouble grasping why the code after “else” grabs the middle integer in lists with odd numbers of integers. I’m trying to translate it into English in my head, but it seems like it would be saying "divide the total amount of integers(5) in half and return the integer occupying that space, which doesn’t exist since it would be the integer at 2 1/2 space. Happy to elaborate further if this isn’t making much sense. Thanks in advance!

Let’s have a list [a, b, c, d, e]:

return lst[int(len(lst)/2)]

I’m going to unwrap it from the inside out:

  • len(lst) = 5
  • divided by 2 = 2.5
  • converted to int, that gets turned into 2 (all the int conversions go down, even if it’s above .5)
  • so we return the index as 2

Looking back at our original list, a is index 0, b is index 1, c is index 2! Our middle index.

Welcome to the forums :slight_smile:

Thank you for breaking it down for me so simply and for the warm welcome.

One mystery from my first week of coding solved! Onto the next 34,546,738.

1 Like