Is there a better/smoother way of doing this ? 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]))
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.