How can I get the index of the middle element?


#1

Question

In the context of this code challenge, how can I get the index of the middle element?

Answer

To get the index of the middle element, or elements, of a list, we must first know whether the list has an odd or even number of elements.

If the list has an odd number of elements, there is only one middle element. As shown in the hint for this exercise, we can get this index using the calculation
int(len(list) / 2)

For example,

list = [1, 2, 3, 4, 5]

middle = int(len(list) / 2) # = int(2.5) = 2
print(list[middle]) # 3

If the list has an even number of elements, then there are two middle elements, and thus two indices that we need to calculate. To get these indices, we can use the following calculations:

# First middle element
int(len(list) / 2) - 1

# Second middle element
int(len(list) / 2)

For an example,

list = [1, 2, 3, 4, 5, 6]

first_middle = int(len(list) / 2) - 1 # = 3 - 1 = 2
second_middle = int(len(list) / 2)    # = 3

print(list[first_middle])  # 3
print(list[second_middle]) # 4