Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Darius Bashar
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.
Here is an example of how the error occurs.
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.
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.
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.
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
print(10/2) # 👉️ 5.0
Division /
of integers yields a float, while floor division //
of integers
results in an integer.
print(10//2) # 👉️ 5
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.
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.