根本原因是索引i超出列表合法范围:正索引需满足0≤i

为什么访问 list[i] 会突然报 IndexError: list index out of range
根本原因只有一个:你试图用一个超出列表合法索引范围的整数去取值。Python 列表索引从 0 开始,最大有效索引是 len(lst) - 1;负索引从 -1(末尾)开始,最小有效负索引是 -len(lst)。越界就炸,不商量。
常见诱因包括:
- 循环里用
range(len(lst) + 1)或range(1, len(lst)+1),多跑一轮 - 删除元素后仍按原长度遍历(比如边
pop()边for i in range(len(lst))) - 解析外部数据(如 CSV 行、API 返回数组)时没校验长度,直接硬取
row[2] - 递归或状态机里索引变量未重置或意外递增过头
用 if i 防御还是用 <code>try/except 捕获?
取决于场景。防御性检查适合「索引由逻辑推导而来,本不该越界」的情况;异常捕获更适合「索引来自不可控输入,且失败是预期中的分支」。
例如处理用户输入的字段序号:
def get_field(data, idx):
try:
return data[idx]
except IndexError:
return None # 或默认值、日志告警
而如果是遍历已知结构的配置列表,更该在入口处断言或提前校验:
if len(config) <p>注意:<code>try/except</code> 不影响性能(未抛异常时开销极小),但滥用会掩盖真实逻辑错误。</p><h3>用 <code>enumerate()</code> 和 <code>for item in lst</code> 替代 <code>for i in range(len(lst))</code>
</h3><p>90% 的越界问题源于手动管理索引。能不碰 <code>i</code> 就别碰。</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill8910" title="361SCAN security check your skill python scripts"><img
src="https://img.php.cn/upload/skill/000/000/081/179231049778675.jpg" alt="361SCAN security check your skill python scripts" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill8910" title="361SCAN security check your skill python scripts" class="overflowclass">361SCAN security check your skill python scripts</a>
<p class="overflowclass">扫描并分析已安装技能,用于查看指定技能目录的名称、描述和详情,或列出所有已安装的技能。</p>
</div>
<a rel="nofollow" href="/xiazai/skill8910" title="361SCAN security check your skill python scripts" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><p>以下写法危险:</p><pre class="brush:python;toolbar:false;">for i in range(len(items)):
process(items[i]) # 如果 items 在循环中被修改,i 可能越界
推荐写法(安全、简洁、意图清晰):
- 只读遍历 →
for item in items: - 需要索引 →
for i, item in enumerate(items): - 需要反向遍历 →
for item in reversed(items):或for i in range(len(items)-1, -1, -1):(后者务必确认items不变)
enumerate() 生成的 i 是当前迭代的真实位置,不受中间 del、pop() 影响 —— 因为它不依赖 len() 动态计算。
调试时怎么快速定位是哪一行、哪个索引出的问题?
不要靠猜。在报错行前后加一句打印:
print(f"len(lst)={len(lst)}, i={i}, lst={lst!r}")
result = lst[i]
更稳妥的是启用 Python 的详细 traceback(默认已有),重点看最后一行报错位置,再往上找调用栈里谁传了非法 i。如果是在复杂嵌套里,临时加 assert i = -len(lst), f"i={i} out of bounds for {len(lst)}" 比捕获异常更能暴露源头。
另外,PyCharm / VS Code 调试器里直接把鼠标悬停在 lst[i] 上,会显示 lst 当前内容和长度,比反复 print 快得多。
越界本身简单,难的是它常是上游逻辑失控的表象——比如本该过滤空行却漏了,导致后续按固定列数解析时崩在第 0 行。盯住报错位置,但更要顺藤摸到那个没做长度判断的上游调用点。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










