Skip to content

IndexError: 列表索引 out 的范围

错误信息

                列表索引 out 的范围
              

快速摘要

你 tried 到 access 列表元素 at 索引那个是 超出列表's 有效范围 (0 到 `len(列表) - 1`).

为什么发生

  • 索引是 greater than or equal 到列表长度

  • 列表是 空但 是 accessed at 索引 0

  • Off-通过-one 错误 in 循环边界 (e.g., 范围(len(lst) + 1))

最小示例

✗ 错误代码
nums = [1, 2, 3]
print(nums[5])
✓ 修复代码
nums = [1, 2, 3]
print(nums[2])

nums[5] 是 out 的范围 — 列表有 3 元素 (索引 0–2). Use 有效索引如 nums[2] 到 access 最后元素.

如何诊断

  • Print len(lst) and 索引是 accessed

  • 检查循环边界 — 做索引 stay 在内 0 到 len(lst) - 1?

  • 验证列表是 不空 之前 accessing 元素

如何修复

  • 检查 如果索引 < len(lst) 之前 accessing 元素

  • Fix 循环边界 (use 范围(len(lst)), 不 范围(len(lst) + 1))

  • Use try/except IndexError 到 handle 错误 gracefully

如何预防

  • Prefer for 项 in lst over for i in 范围(len(lst)) 当可能

  • 检查列表长度之前 accessing 通过索引

相关资源

相关术语

相关课程

相关练习

← 返回语言