# Python - List code practice middle_element question

Hi,

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.

def middle_element(my_list):
list_len = len(my_list)
if list_len % 2 == 1:
return my_list[int(list_len)]
else:
element_1 = my_list[int(list_len/2) - 1]
element_2 = my_list[int(list_len/2)]

``````return (element_1 + element_2)/2
``````

#Uncomment the line below when your function is done
print(middle_element([5, 2, -10, -4, 4, 5]))

Thanks

It could be an indentation issue. We can’t really tell b/c your code isn’t formatted.

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.

I think you forgot a   `/2` in one of the list indices.

I formatted the code in the previous post to have the appropriate indentations:

``````def middle_element(my_list):
list_len = len(my_list)
if list_len % 2 == 1:  # list_len is odd
return my_list[int(list_len)]  # the /2 is missing here
else:  # list_len is even
element_1 = my_list[int(list_len/2) - 1]
element_2 = my_list[int(list_len/2)]
return (element_1 + element_2)/2
``````
1 Like

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
``````
2 Likes

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.