8
3

More than 3 years have passed since last update.

【python】エラー原因と対処法:slice indices must be integers or None or have an __index__ method

Posted at

pythonで下記エラーが発生したので、発生原因と対処法メモ。

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

エラー詳細

スライスで変数を指定した際に発生。

arr = [1,2,3,4,5,6]
mid = len(arr)/2   #エラーの原因

print(arr[0:mid])  #エラー発生処理

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

エラーの内容は、スライスでは整数か、値未記入か__index__メソッドのどれかしか指定できないとのこと。

__index__メソッドとは、typeでintを返す処理のこと。


エラーの原因と対処法

エラーの原因は、len(arr)/2がint(整数)でなかったことによる。
割り算のスラッシュは、対象が偶数の場合でも小数点0を含むfloatになる。

arr = [1,2,3,4]
type(len(arr)/2)

#float

対処法

スラッシュ2つを使う。「/」→「//」
スラッシュ2つは割り算の整数部のみ(小数点以下切り捨て)

typeの確認
arr = [1,2,3,4]
type(len(arr)//2)

#int


再計算
arr = [1,2,3,4,5,6]
mid = len(arr)//2

print(arr[0:mid])

#[1, 2, 3]
8
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
3