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 lstoverfor i in 范围(len(lst))当可能检查列表长度之前 accessing 通过索引
相关资源
相关课程
- 条件 and 循环
学习关于循环 and 列表 iteration in Python
相关练习
- Python 动态输入
理解 Python's 类型系统 for 列表.