TypeError: slice indices must be integers or None or have an __index__ method

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: slice indices must be integers or None or have an __index__ method #

The Python "TypeError: slice indices must be integers or None or have an __index__ method" occurs when we use a non-integer value for slicing (e.g. a float). To solve the error, make sure to use integers when slicing a list, string or any other sequence.

typeerror slice indices must be integers or none or have index method

Here is an example of how the error occurs.

main.py
my_list = ['a', 'b', 'c', 'd'] start = 0.5 stop = 2.5 # ⛔️ TypeError: slice indices must be integers or None or have an __index__ method result = my_list[start:stop]

We used floats for the start and stop values when slicing the list.

When slicing a sequence, we need to use integers for the start, stop and step values.

The syntax for list slicing is my_list[start:stop:step].

To solve the error, convert the floating-point values to integers.

main.py
my_list = ['a', 'b', 'c', 'd'] start = 0.5 stop = 2.5 result = my_list[int(start):int(stop)] print(result) # 👉️ ['a', 'b']

We passed the floating-point numbers to the int() class to convert them to integers.

Note that the value for start is inclusive whereas the value for stop is exclusive.

The error often occurs when we use the division operator / because the division operator / always produces a float value

main.py
print(10/2) # 👉️ 5.0

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

main.py
print(10//2) # 👉️ 5
The result of using the floor division operator is that of a mathematical division with the floor() function applied to the result.

Once you use integers to slice the sequence, the error will be resolved.

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

main.py
my_int = 10 print(type(my_int)) print(isinstance(my_int, int)) my_float = 3.14 print(type(my_float)) print(isinstance(my_float, float))

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: slice indices must be integers or None or have an __index__ method" occurs when we use a non-integer value for slicing (e.g. a float). To solve the error, make sure to use integers when slicing a list, string or any other sequence.

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.