- 最終更新
- 2026/08/17
3秒でわかる
Python でリストの範囲外を指したときに出る例外。件数と添字のずれを知らせる合図なので、境界の条件を見直す手がかりになります。
30秒図解
もう少し詳しく
どういうものか
IndexError は、リストやタプルなどのlst[3] を
添字は
なぜ必要か
黙って
具体例
items = ["a", "b", "c"]
print(items[2]) # c 最後の要素
print(items[3]) # IndexError: list index out of range
print(items[-1]) # c 末尾から数える書き方は範囲内エラー表示は
Traceback (most recent call last):
File "app.py", line 5, in <module>
print(items[3])
IndexError: list index out of range安全に
for item in items:
print(item)
# 番号も欲しいときは enumerate を使う
for i, item in enumerate(items):
print(i, item)つまずきやすいところ
range(len(items) + 1) のように上限を 1 つ足してしまうrange(3) はrange(len(items)) で
ループの中で remove や pop を
外部split(",") でtry で
似た用語との違い
| 例外 | 起きる状況 |
|---|---|
| IndexError | リストの |
| KeyError | 辞書に |
| TypeError | 型が |
| ValueError | 型は |
覚え方
「最後の


