The following error occurred in python, so the cause and remedy memo.
TypeError: slice indices must be integers or None or have an __index__ method
Occurs when a variable is specified in a slice.
python
arr = [1,2,3,4,5,6]
mid = len(arr)/2 #Cause of error
print(arr[0:mid]) #Error occurrence processing
#TypeError: slice indices must be integers or None or have an __index__ method
The content of the error is that you can only specify an integer, no value, or the __index__
method in the slice.
__index__
method is a process that returns an int by type.
The cause of the error is that len (arr) / 2 was not an int (integer). The slash for division is a float that includes the decimal point 0 even if the target is even.
python
arr = [1,2,3,4]
type(len(arr)/2)
#float
Use two slashes. "/" → "//" Two slashes are only the integer part of division (rounded down to the nearest whole number)
Confirmation of type
arr = [1,2,3,4]
type(len(arr)//2)
#int
Recalculation
arr = [1,2,3,4,5,6]
mid = len(arr)//2
print(arr[0:mid])
#[1, 2, 3]