TypeError: list indices must be integers or slices not float

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: list indices must be integers or slices not float #

The Python "TypeError: list indices must be integers or slices, not float" occurs when we use a floating-point number to access a list at a specific index. To solve the error, convert the float to an integer, e.g. my_list[int(my_float)].

typeerror list indices must be integers or slices not float

Here is an example of how the error occurs.

main.py
my_list = ['a', 'b', 'c'] my_float = 1.0 # ⛔️ TypeError: list indices must be integers or slices, not float result = my_list[my_float]

We used a float to access the list at an index which caused the error.

To solve the error, convert the float to an integer.

main.py
my_list = ['a', 'b', 'c'] my_float = 1.0 # ✅ convert float to int result = my_list[int(my_float)] print(result) # 👉️ 'b'

The int class returns an integer object constructed from the provided number or string argument.

We have to use an integer (e.g. my_list[2]) or a slice (e.g. my_list[0:2]) for list indices.

The error is often caused when using the division / operator which always returns a floating-point number.

main.py
my_list = ['a', 'b', 'c'] my_float = 4 / 2 print(my_float) # 👉️ 2.0 result = my_list[int(my_float)] print(result) # 👉️ 'c'

We used the division operator with 2 integers and still got a float.

You can use the floor division // operator if you need to get an integer result.

main.py
my_list = ['a', 'b', 'c'] my_int = 4 // 2 print(my_int) # 👉️ 2 result = my_list[my_int] print(result) # 👉️ 'c'

Division / of integers yields a float, while floor division // of integers results in an integer.

If you need to get a slice of a list, use a colon to separate the start and end indices.

main.py
my_list = ['a', 'b', 'c', 'd', 'e'] print(my_list[0:3]) # 👉️ ['a', 'b', 'c'] print(my_list[3:]) # 👉️ ['d', 'e']

The start index is inclusive, whereas the end index is exclusive (up to, but not including).

If you aren't sure what type of object a variable stores, use the type() class.

main.py
my_float = 3.14 print(type(my_float)) # 👉️ <class 'float'> print(isinstance(my_float, float)) # 👉️ True

The type class returns the type of an object.

The isinstance function returns True if the passed in object is an instance or a subclass of the passed in class.

Conclusion #

The Python "TypeError: list indices must be integers or slices, not float" occurs when we use a floating-point number to access a list at a specific index. To solve the error, convert the float to an integer, e.g. my_list[int(my_float)].

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.