Here is the code im referring to:
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]))
This is the Codeacademy solution to finding the middle element. If the list has an even amount of elements, the middle two elements are averaged out. If the list has an odd amount of elements, it just returns the middle element.
I’m struggling to work out how the two middle elements are called, as on line 4 it says:
sum = lst[int(len(lst)/2)] + lst[int(len(lst)/2) - 1]
Looking at this, I can see that it grabs the size of the list, and halves it, which is 2 (the third element). then on the second part of the code, it grabs the length of the list, halves it, then minus’s 1 from the halved number, which is 1? Why is it calling 1 (the second element) rather than calling 3 (the fourth element)
The code runs fine so i know its an issue with my understanding rather than the code, but im struggling to understand why it uses - 1 rather than +1.
Could anyone tell me in laymen’s terms why - 1 is used please?