【Python】「list index out of range」の解決方法

こんにちは、にわこまです!
今回は、pythonでリストを扱っているときに発生する「list index out of range」の解決方法を解説します。
スポンサードサーチ
「list index out of range」の解決方法
リストの要素数を超えて参照しない。
上記を実施することで「list index out of range」を解決できます。
そもそも「list index out of range」は「リストの範囲を超えて参照しているよ」というエラーです。
例えば、要素が5つしかないリストに対して6つ目を参照しようとすると、範囲外なのでエラーが発生します。
エラーのサンプルコード
エラーが発生するサンプルコードと実行結果を以下に示します。
fruits = ["apple", "banana", "cherry", "grape", "lemon"]
print(fruits[0])
print(fruits[1])
print(fruits[2])
print(fruits[3])
print(fruits[4])
print(fruits[5])
===== 実行結果 =====
apple
banana
cherry
grape
lemon
Traceback (most recent call last):
File "C:\Users\niwakomka\python\tmp.py", line 8, in <module>
print(fruits[5])
IndexError: list index out of range
上記のサンプルコードはリストの要素を1つずつ表示するサンプルコードです。
6つ目の要素がないのに参照しようとしてエラーが発生しています。
6つ目の参照を削除することでエラーを解決できます。
エラーを解決したサンプルコードと実行結果を以下に示します。
fruits = ["apple", "banana", "cherry", "grape", "lemon"]
print(fruits[0])
print(fruits[1])
print(fruits[2])
print(fruits[3])
print(fruits[4])
===== 実行結果 =====
apple
banana
cherry
grape
lemon
まとめ

今回は「list index out of range」の解決方法について解説しました。
改めて解決方法を以下に示します。
リストの要素数を超えて参照しない。
解決してほしいエラーや問題がありましたらメールまたはTwitterのDMまで!
最後までお読みいただきありがとうございます。
スポンサードサーチ