MeWrite Docs

StopIteration

Pythonでイテレータが終了した際に発生する例外

概要

StopIteration は、イテレータの next() を呼び出した際に、これ以上要素がない場合に発生する例外です。通常はforループが自動的に処理しますが、手動でnext()を使う場合は注意が必要です。

エラーメッセージ

StopIteration
RuntimeError: generator raised StopIteration

原因

1. next()でイテレータを使い切った

1
2
3
4
items = iter([1, 2])
print(next(items))  # 1
print(next(items))  # 2
print(next(items))  # StopIteration

2. 空のイテレータでnext()を呼び出し

1
2
empty = iter([])
print(next(empty))  # StopIteration

3. ジェネレータ内でStopIterationをキャッチしない(Python 3.7+)

1
2
3
4
5
6
def gen():
    it = iter([1, 2])
    while True:
        yield next(it)  # Python 3.7+ではRuntimeErrorになる

list(gen())  # RuntimeError: generator raised StopIteration

解決策

1. デフォルト値を指定

1
2
3
4
items = iter([1, 2])
print(next(items, None))  # 1
print(next(items, None))  # 2
print(next(items, None))  # None(エラーなし)

2. forループを使用

1
2
3
4
5
items = [1, 2, 3]

# forループは自動的にStopIterationを処理
for item in items:
    print(item)

3. try-exceptで処理

1
2
3
4
5
6
7
8
items = iter([1, 2])

try:
    while True:
        item = next(items)
        print(item)
except StopIteration:
    print("イテレーション完了")

4. ジェネレータでの正しい処理(Python 3.7+)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
# NG: StopIterationがRuntimeErrorになる
def gen_bad():
    it = iter([1, 2])
    while True:
        yield next(it)

# OK: 明示的に終了する
def gen_good():
    it = iter([1, 2])
    for item in it:
        yield item

# OK: try-exceptで処理
def gen_also_good():
    it = iter([1, 2])
    while True:
        try:
            yield next(it)
        except StopIteration:
            return

5. itertools.chain を使用

1
2
3
4
5
6
from itertools import chain

# 複数のイテレータを連結
combined = chain([1, 2], [3, 4])
for item in combined:
    print(item)

Python 3.7以降の変更

Python 3.7以降、ジェネレータ内でStopIterationが発生するとRuntimeErrorに変換されます。

1
2
3
4
5
6
7
8
# Python 3.6以前: 正常終了
# Python 3.7以降: RuntimeError
def problematic_gen():
    raise StopIteration  # NG

# 正しい方法
def correct_gen():
    return  # ジェネレータを終了

関連エラー

関連エラー

Python の他のエラー

最終更新: 2025-12-17