I’m looking at the code practice for lists. I don’t see why my code doesn’t past the checker. It gives the right answer.

Question is below:

Create a function called middle_element that has one parameter named my_list.

If there are an odd number of elements in my_list, 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.

Also, did you have a chance to peruse the forums for this question? There’s several posts that might help you glean some insights as to why your code doesn’t work.

Why so many repeated operations/expressions? Given you have found an error, would it not be helpful to discuss how to avoid that mistake in future? How many times do we need to divide the length by 2? Answer: 1.

n = len(my_list)
m = int(n / 2)

The only operations left to perform will involve one or the other of the above cached values. The remainder operation is used to control flow, and the averaging operation needed when the length is even.

What do we know about those two variables? Well, n is the length, and more importantly, m is the index of the midpoint in an odd length list. In an even length list m is the index of the ‘higher order’ element, and that the ‘lower order’ index (1 less) is the co-addend of the middle pair of the list (ordered or unordered). Values mean nothing at this point, only the middle pair of values.

So that covers it and offers a way to not have to repeat ourselves (in code).

if n % 2:
return my_list[m]
return (my_list[m - 1] + my_list[m]) / 2

m - 1 m
\ /
[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] <<< list elements
^ ^
/ \
lower higher
order order