I am getting a data type error:
length2 = (len(lst) / 2 - 1)
print(length2)
position2 = lst[length2]
length3 = (len(lst) / 2)
print(length3)
position3 = lst[length3]
#finds average
average = (position2 + position3) / 2
Output:
2.0
Traceback (most recent call last):
File "script.py", line 26, in <module>
print(middle_element([5, 2, -10, -4, 4, 5]))
File "script.py", line 12, in middle_element
position2 = lst[length2]
TypeError: list indices must be integers or slices, not float
However I feel like my code/logic is correct?
Create a function called
middle_element
that has one parameter namedlst
. If there are an odd number of elements inlst
, 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.
#Write your function here
def middle_element(lst):
length = len(lst)
#takes the length and divides it by 2 to return the middle element
half_of_length = length / 2
#modulo by 2 to determine if it is odd
if length % 2 != 0:
return half_of_length
length2 = (len(lst) / 2 - 1)
print(length2)
position2 = lst[length2]
length3 = (len(lst) / 2)
print(length3)
position3 = lst[length3]
#finds average
average = (position2 + position3) / 2
#finds if the lst is even
if length % 2 == 0:
return average
#Uncomment the line below when your function is done
print(middle_element([5, 2, -10, -4, 4, 5]))