# Python Code Challenges: Lists (Advanced) - 5. Middle Item

Hi,

I got stuck on the last assignement on the advanced part of lists.

I wrote the code with the correct functions, all though i tried to use floats in the even-number part.

However, I cannot wrap my head around the part for odd numbers. Let´s assume we have 7 elements in our list, i.e. len(str) is odd. Codecademy suggets we call str[int(len(str)/2)] which i do not understand, since len(str)/2 equals 3.5, but then we force it to become a integer which is resonable.

But if i create a variable i and set it equal to 3.5 then prints it, it will not be 4, as it prints 3.5 when i try it. Code example below. Then how does is manage to call for index 4 and be correct in the example above and fully copied below? Please advise!

i = 3.5
print(int(i))

Output: 3.5

``````#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 = 3.5
print(int(i))
``````

Should print 3 as it truncates the decimals (note: this is not the floor function). Are you sure this is printing 3.5?

2 Likes

Hi,
Remember arrays start at index 0, so the middle of an array of length 7 will be 3.
Not sure why you’re getting an output of 3.5
When I try it gives me 3.

Hi,

Thanks!

Yes it´s correct as you say that the index starts at 0, however the len() function does not. Hence, if we have 7 indices for instance, the len() will be 7, i.e. len(str)/2 will return 3.5 which is not a valid index.

which should be the case using this function as they do:
"
else:
return lst[int(len(lst)/2)]
"

But as we do it with int, you say this should truncate it to three, which then would return the correct number?

Now as i try the int() function in print with i = 3.5 it seems to truncate correctly, might have been something wrong yesterday…

thanks!

1 Like

Must have been me who did something wrong yesterday while tired, worked perfectly today!

Thanks!

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.