Advanced Python Code Challenges: Lists, Question #5

Hi there,

Here is the link to the quiz I am working through:

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


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.

1 Like

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

1 Like

Hi, Thanks for your solution, which does give the right solution. I had a query (maybe I am overthinking this).

should the syntax be lst[int(len((lst)/2) + 1] as in an even number of elements, you want the middle and middle plus 1?

you could do the math. Take a even list length (lets say 4), then the indexes are: 0, 1, 2, 3

so the middle two items are positioned at index 1 and 2.

4 (the length) divided by 2 gives 2. So now we have the right middle value.

Teaching yourself these thinking steps is so crucial