 # Advanced Python Code Challenges: Lists, Question #5

Hi there,

The last questions asks me to create a function called “middle_element” with a single parameter “lst.” Then return an average of the middle elements if the list is even, or return the middle element (singular) if the list is odd. The answer code is below, and my question is below that.

``````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, 4, -10, -4, 4, 5]))
``````

This returns -10 as the middle element, which is correct, but I don’t understand something about the block of code behind the else statement that leads to that outcome. It seems that this would take the length of lst which is 7, then divide by 2, meaning 3.5 and access lst at that element position. But then it returns the 3rd element, the -10, somehow. Two questions follow: can you access lists using floats that somehow round up or down to a particular element? Or how else can that else statement access the correct element at position 3? Am I just doing addition wrong or something? It’s been a long day haha.

Thanks!

floats can not be used to access elements at certain position index, go ahead, try, you will get an error

which is why you use `int()`, which rounds down to nearest integer.

Got it, thanks a lot! I didn’t know int() rounds down. Cheers.