How can I get the index of the middle element?

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
3 Likes

Hey, this is really and interesting methodology. I didn’t think about it like that. My first instinct was to use the modulus approach, which when the length is divisable by 2, you would have an even length. Here was my approach…but still not fully complete.

def middle_element(lst):
  if len(lst) % 2 != 0:
    return lst.index(range(lst) // 2)
  else:
    return len(lst) // 2 + len(lst) // 2 - 1
1 Like

Hi everyone hope this helps out it is the answer I came up with for this lesson.

#Write your function here
def middle_element(lst):
  if (len(lst) % 2 == 0):
    len_list = len(lst)
    half_list = int(len_list/2)
    middle_list = lst[half_list-1:half_list+1]
    total_list = sum(middle_list)/2
    return total_list
  
  elif (len(lst) % 2 != 0):
    odd_len_list = len(lst)
    int_list = int(odd_len_list + 1)/2
    mid_odd_list = lst[int(int_list-1):int(int_list)]
    rm_item = mid_odd_list.pop()
    return rm_item

  else:
    return "You have an error in your program! Sorry!!"

1 Like

Trying to stick to just what has been taught in the lesson plan, not including the excellent contributions of forum contributors, I came up with this:

def middle-element(1st):
middle = int(len(last) / 2) # ensuring value generated for use as an index is an integer
if len(lst) % 2 != 0: # ensuring than for ‘condition A’, we are working with an even number
return lst[middle] # since this slice is from a zero index list, the index is correct.
else: # allowing for ‘condition B’, an odd numbered value for ‘len’
return (last[middle - 1] + lost[middle]) / 2 # index value must be adjusted to previous value

Hi fellow students,

How come list[int(len(list) / 2)] doesn’t work?

Thank you!

Below is what i came up with.

def middle_element(lst):
  if len(lst)%2 == 0:
    element_1 = int(len(lst)/2)
    element_2 = int(len(lst)/2) - 1
    return (lst[element_1] + lst[element_2]) / 2
  else:
    element = int(len(lst)/2)
    return lst[element]

I’m trying to use only what I’ve learnt, would there be any issues with my code?
last couple of challenges have been a bit more difficult.

1 Like

A little bit sketchy but works…

def middle_element(lst):
  if len(lst) % 2 != 0:
    return lst[int(len(lst) / 2)]
  else:
    return (((lst[int(len(lst) / 2)]) + (lst[int(len(lst) / 2) - 1])) / 2)
2 Likes

I made it work with this.

def middle_element(lst):
  if (len(lst)%2 == 0):
    index1= lst[int(len(lst)/2)]
    index2= lst[int(len(lst)/2) -1]
    return (index1+index2)/2
  else:
    return lst[int(len(lst)/2)]
1 Like

my solution :

def middle_element(lst):
  half_len = int((len(lst) / 2))
  if len(lst) % 2 == 0:
   return (lst[half_len -1] + lst[half_len]) / 2
  else:
   return lst[half_len]
2 Likes

why do we have to make (len(lst)/2) an int?

What about
len(lst)//2

I’m pretty sure it’s because the function list is made to convert things such as “range(3, 10, 6)”, and not single integers. For example it would work with zip or range because the give the function list info other than an integer

Because otherwise it will be a float and not an integer. That causes an error telling you that indexs can only be integers and not floats.

hi, this was my solution, it’s not the best but thought it may help

#Write your function here
import math
def middle_element(lst):
  len_lst = len(lst)
  if len_lst % 2 == 0:
    half = int(len_lst / 2)
    middle = lst[half - 1:half + 1]
    median = sum(middle)/2
    return median 
  else:
    return lst[math.ceil(len_lst/2) - 1]
      

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

def middle_element(lst):
if len(lst)%2 != 0:
x1 = (len(lst)/2)-0.5 #x1 is the index, -0.5 because for example, 3 is the middle element of 7, 7/2 = 3.5, -0.5 finds the index 3, which because of indexes starting at 0, its the middle one.
x1 = int(x1) #x1 float to int
return lst[x1]
else:
x1 = (len(lst)/2) #x1 is the index
y2 = x - 1
y2 = int(y2)
x1 = int(x1)
z3 = (lst[y2]+lst[x1])/2
return z3

Mine was similar to yours!

#Write your function here

def middle_element(lst):
  lst_len = int(len(lst))
  if len(lst) % 2 != 0:
    return lst[lst_len // 2]
  else:
    return ( lst[int(lst_len/2)-1] + 
    lst[int(lst_len/2)] ) / 2

len() returns an integer, so no need to cast it as one.

You have a variable for len(lst) so you could use that, instead.

Welcome to the forums!

Let’s break this statement down.

lst[index] is used to access the element at index index in the list. Now, index can be any integer, expression, etc. as long as an integer is the final result.

In this case, the element we are trying to access is at index int(len(lst) / 2). Let’s break this down further.


len(lst) here is used to get the length of the list. So if I had a list as follows: [0, 2, 4], and I called the len() function on it, it would return 3.

We then divide the list by 2 using len(lst) / 2, which gives us the middle index. If the length of our list is odd, say 3, this expression would return 1.5. If the length of our list is even, say 4, this expression would return 2.

We then use the int() function on the entire statement of len(lst) / 2. int() truncates the decimal portion of the value that is passed into it. So, if len(lst) / 2 gave us 1.5, using int() would return a result of 1. If len(lst) / 2 gave us 2, using int() would return 2.


Now that we have the index of the middle element, we access it by using lst[]. Note that return lst[int(len(lst) / 2) will return the middle element in a list with an odd number of elements (2 is returned from [0, 2, 4]) and the higher of the two middle elements will be returned in a list with an even number of elements (4 is returned from [0, 2, 4, 6]).


Example
>>> lst = ["a", "b", "c"]
>>> lst2 = ["d", "e", "f", "g"]
>>>
>>> lst[int(len(lst) / 2)]
b
>>> lst2[int(len(lst) / 2)]
f
1 Like

I know the answer is probably pretty obvious but I am having a hard time understanding why we -1 from one of the half. Can anyone break that down for me?

It is to capture the middle pair.

Say we have list (s) with length 12, so let n = 12.

m = n // 2

Floor divide so we get an integer. In this case it will be, 6.

0 1 2 3 4 5 6 7 8 9 10 11  <= the indices of the list.

Note that 6 is in the right side half, leftmost. Minus 1 gives us 5 which is the rightmost of the left side half. So the middle pair will be at index[5] and index[6]. We are told to return the average.

return (s[m-1] + s[m]) / 2    #  note float division