Code Challenge (List) - Middle Item help

  1. Middle Item

For the final code challenge, we are going to create a function that finds the middle item from a list of values. This will be different depending on whether there are an odd or even number of values. In the case of an odd number of elements, we want this function to return the exact middle value. If there is an even number of elements, it returns the average of the middle two elements. Here is what we need to do:

  1. Define the function to accept one parameter for our list of numbers
  2. Determine if the length of the list is even or odd
  3. If the length is even, then return the average of the middle two numbers
  4. If the length is odd, then return the middle number

Below is my attempt:

def middle_element(my_list):
if len(my_list) % 2 == 0:
return my_list[len(my_list/2)] + my_list[(len(my_list/2)-1] / 2
else:
return my_list[len(my_list)/2-0.5]

Why did it return a syntax error? The default answer uses the int function. Is it possible to solve the challenge without using int at all, as I tried to do?

I can’t see the indentations in the code. Use the </> button for that.

You can subtract before dividing so that you don’t have to deal with floats like 0.5 at all.
return my_list[ (len(my_list) - 1) // 2 ]
Notice the use of // for integer division in Python 3.

Yes, I know that return my_list[ len(my_list) // 2 ] would work too.

print(15 / 3) print(15 // 3)

Note that the average of a and b would be (a + b) / 2,
but not a + b / 2

1 Like

Bear in mind that Python data structures that are indexable have zero-based indices. This is important.

The midpoint of an even lengthened list is the same as an odd length list. if computed with division. Keep in mind we want an integer midpoint.

>>> 9 // 2
    4
>>> 8 // 2
    4
>>>

It is up to us to leverage that quotient, along with knowledge of the actual length.

We can also leverage negative indexing; that is, right to left accessing. I’ll leave that for you to explore. We’ve discussed this in recent posts.

Finding a median is not the greatest difficulty if we have a working plan.

2 Likes

That’s super helpful. Thank you!

Thanks for these edifying thoughts!