List indices must be integers or slices, not numpy.float64

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

List indices must be integers or slices, not numpy.float64 #

The Python "TypeError: list indices must be integers or slices, not numpy.float64" occurs when we use a numpy float 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 numpy float64

Here is an example of how the error occurs.

main.py
import numpy as np my_float = np.float64(1.14) my_list = ['a', 'b', 'c'] # ⛔️ TypeError: list indices must be integers or slices, not numpy.float64 result = my_list[my_float]

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

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

main.py
import numpy as np my_float = np.float64(1.14) my_list = ['a', 'b', 'c'] # ✅ convert numpy 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.

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
import numpy as np my_float = np.float64(1.14) print(type(my_float)) # 👉️ <class 'numpy.float64'> print(isinstance(my_float, np.float64)) # 👉️ 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 numpy.float64" occurs when we use a numpy float 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.