Doing the “Middle Item” challenge, I was shown the following solution:
#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]
return sum / 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]))
I am looking for an explanation for this part:
else:
return lst[int(len(lst)/2)]
If the length of the list is and odd number how is this handled? Example with a length of ‘5’.
This is ‘5/2 = 2.5’
How does it know what the correct index number is? It is also not a division with ‘//’ that it would end up with an integer.
Exercise link (exercise 5):
https://www.codecademy.com/paths/computer-science/tracks/cspath-flow-data-iteration/modules/dspath-lists/articles/advanced-python-code-challenges-lists