5. Middle Item Question about efficiency/improving my code

Welcome to the Get Help category!
Hello, Question 5 of https://www.codecademy.com/paths/data-science/tracks/dscp-python-fundamentals/modules/dscp-python-lists/articles/advanced-python-code-challenges-lists

Is there a better/smoother way of doing this ? :slight_smile: Thanks

#Write your function here
from statistics import mean

def middle_element(lst):
  if len(lst) % 2 == 0:
    return mean(lst[(len(lst)-1)//2:(len(lst)+2)//2])
  elif len(lst):
    return lst[int(len(lst)/2)]

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

To find the middle element of an unordered list we need two pieces of information:

n = len(lst)
m = n // 2

That’s enough information cached to make short work of the rest.

The length has a bearing on whether the middle is one element (odd length) or two (even length).

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

If the list is ordered, the return will be the median.

Hi there, i’m a bit new.

s you create 2 new variables?

n = len(lst)
m = n // 2

Where do you put these variables? and can you show how your solution works within the problem itself?

Thanks for your help.

1 Like

Ah, I thought this was about the middle item, not a way to extract a sub-sequence.

We’re given two numeric parameters which are both indices meaning we can, as you have, use the slice method to virtualize it.

lst[start:end + 1]

describes the segment we wish to remove. If we want to keep it, we can assign it to a new variable. It could also be used in a transient expression (one-off then it is gone). Either way, we get rid of the slice by setting it to an empty list.

lst[start:end + 1] = []

This is a totally different operation than the one envisioned above.


Above I use the term virtualize. Slices do not raise an IndexError when given garbage.

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