Hello, somebody can help me to understand this code?

#Write your function here
def middle_element(lst):
if len(lst) % 2 == 0:
sum = lst[int(len(lst)/2)] + lst[int(len(lst)/2) - 1] #this part I can’t understand!=(
return sum / 2 # why we need to / by 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]))

have you try to use print() to see what is going on?

It also helps to understand what the code does in the first place. Lets say i have the following list:

[4, 4, 5, 5]

and from this lists i need the middle value, how would this be achieved? We get the middle two values (4 and 5), add them together and divided it by 2 to get the average

2 Likes