Why the ‘list’ command?


#1

Middle Item

What I do not understand about this exercise is why the ‘list’ command, which is supposed to give you the length of the total list, gives you a number that is actually in the list.

Using my logic, this:

sum = lst[int(len(lst)/2)] + lst[int(len(lst)/2) - 1]

should return: length of the list, 6, devided by 2 = 3 + lentgh of the list, again, 6, divided by 2, = 3, then - 1 = 5
instead it takes the middle 2 numbers, is that because of int? I thought that was just to indicate a number.


FAQ: Code Challenge: Lists - Middle Item
FAQ: Code Challenge: Lists - Middle Item
#2

sum = lst[int(len(lst)/2)] + lst[int(len(lst)/2) - 1]

so len(lst) is returning 6. 6 / 2 is an index of 3.
so that’s the 4th element, ie, -4
so then it’s doing the same thing, 6/2 = 3. now it’s subtracting 1, which gives us a index of 2.
which means the 3rd element -10

print(middle_element([5, 2, -10, -4, 4, 5]))


#3

When something is getting complicated, it needs to be simplified to remove repetition.

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

Now we can add the two with ease…

sum = lst[m - 1] + lst[m]

The relates to a statistics concept, median, which will no doubt come up at some point. However, in this exercise we are not sorting the list, only finding the middle one or two elements, depending on parity.


#4

Thanks, I understand now!