[Python] Cause of error and remedy: slice indices must be integers or None or have an __index__ method

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

Error details

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.


## Cause of error and remedy

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

approach

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]

Recommended Posts

[Python] Cause of error and remedy: slice indices must be integers or None or have an __index__ method
[Python] How to deal with the is instance error "is instance () arg 2 must be a type or tuple of types"