Floats, integers

Python Code Challange: Lists (Advanced)
https://www.codecademy.com/courses/learn-python-3/articles/advanced-python-code-challenges-lists
For 5. “Middle Item”
Hi, when I was initially writing code my code for this challenge, I used the line

sum = lst[len(lst)/2 - 1] + lst[len(lst)/2]
This comes up with an error “TypeError: list indices must be integers or slices, not float”

It instead wants me to put
sum = lst[int(len(lst)/2) - 1] + (lst[int(len(lst)/2)])

So my question here is why is the thing I tried a float and what difference does writing int before it do?

In Python 3 there is no integer division like there was in Python 2. All division is float division so even 4 / 4 will return 1.0. Floats cannot be used as indexes.

1 Like

So does that mean that in terms of when I would use ‘int’ in front of things. In the rest of the 'code challenges on that page, ‘int’ isn’t used.

I really appreciate the reply, I’m just a bit confused. Thanks.

1 Like

It’s really a matter of what the end result of any numeric computation will be used for. If it is going to be an index, then it must be an integer. The same would apply if the computed value is going to be used in a range(). With time we learn about the arguments and parameters of various functions and methods which helps us to decide when to use integers.

1 Like