Getting the 2 middle values

#Write your function here
def middle_element(lst):
if len(lst) % 2 == 0:
sum = lst[int(len(lst)/2)] + lst[int(len(lst)/2) - 1]
return sum / 2
else:
return lst[int(len(lst)/2)]

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

///the code above is asking for: Create a function called middle_element that has one parameter named lst .

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

My question is why do we subtract 1 at sum = lst[int(len(lst)/2] + lst[(int(len(lst)/2)-1? If we add one instead of subtracting, will the answer still be correct?

@dev1675940753 I believe this is because list indexes start at zero. This means that the half way point of the list i.e. index 3, is actually the fourth item in the list. You therefore subtract one to get the middle two. Take your list for example:
[5, 2, -10, -4, 4, 5]
The middle (i.e. third item is -10. However, when you access an item in a list, it starts from 0. This means that the item at the 3 index is actually -4, which is the fourth item. Therefore, if you subtract 1, you get the third item (or second, if you are the python compiler), which is -10.
I hope this helps!
Happy coding!

2 Likes

Thanks, makes perfect sense.

1 Like

You’re welcome! Happy coding!

you can use the </> icon to paste your code in

image
image
please assist, l did everything the question is asking for!

image
found the glitch

1 Like

:+1:

I think that was a case of the SCT being a bit picky when it was checking your work.

Sometimes in the editor, you’ll be staring down a red X and wondering why the exercise doesn’t like what you’ve written, only to find that you’ve missed something trivial like a trailing space which didn’t seem immediately relevant.

It can be a little off-putting at points, but keep at it. :+1:

1 Like