I need help in python code challenge (Middle item)


#1

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.

I am so lost i tried more than once but i think i forgot something or i just don’t understand what they want .


#2

the first step is to understand the instructions, lets say we have these two lists:

  1. [1, 2, 3]
  2. [2, 4, 6, 8]

what should be the result of list 1 and what about list 2?


#3

You mean the middle element ? if so i think its

  1. [2]
    2.[4, 6]
    Is that wrong ?

#4

the middle element has a value of 2, so the answer for list 1 is 2, not [2]

list 2 you got it wrong, see instructions:

the function should return the average of the middle two elements


#5

You mean
(2 + 4 + 6 + 8 ) / 4 = 5
?


#6

the average of the two middle values: (left_middle + right_middle) / 2


#7

I feel stupid :sweat: hopefully i am right this time
(4 + 6 ) / 2 = 5


#8

yes, now you understand the task at hand, now comes the next step: implementing

i will leave you too it, see how far you can come? Let me know if you need help if you get stuck (please do share the code then)


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

Finally it worked