Skip to content

手动 next() 调用引发 StopIteration

快速摘要

你对没有更多元素的迭代器调用了 next() —— Python 抛出 StopIteration,如果未捕获会导致程序崩溃。

为什么发生

  • 你调用 next() 的次数超过迭代器的元素数,且未检查是否已耗尽

  • 生成器函数在之前的循环中已被完全消费,你又对同一生成器调用 next()

  • 在不处理 StopIteration 的上下文中(如普通表达式)使用 next() 且未提供默认值

最小示例

✗ 错误代码
it = iter([1, 2, 3])
print(next(it))  # 1
print(next(it))  # 2
print(next(it))  # 3
print(next(it))  # StopIteration!
✓ 修复代码
it = iter([1, 2, 3])
while True:
    val = next(it, None)
    if val is None:
        break
    print(val)  # prints 1, 2, 3

使用 next(it, None) 在迭代器耗尽时返回 None,让你检查并 break 而非抛出 StopIteration。

如何诊断

  • 给 next(it, default) 添加默认参数,使其返回默认值而非抛出 StopIteration

  • 使用 for 循环或 list(it) 安全消费迭代器,而非手动 next() 调用

  • 用 try/except StopIteration 包裹 next() 调用,显式处理耗尽情况

如何修复

  • 给 next(it, None) 传入哨兵默认值,迭代器耗尽时返回 None(或其他默认值)

  • 将手动 next() 循环改写为 for 循环,自然处理迭代完成

  • 用 try/except 捕获 StopIteration,用 break 或 return 干净地退出消费逻辑

如何预防

  • 不确定迭代器是否还有元素时,始终使用 next(it, default) 配合默认值

  • 大多数迭代模式优先使用 for 循环而非手动 next() 调用,完全避免 StopIteration

相关资源

相关术语

相关课程

← 返回语言