python
runtime_error
ai_generated
true
索引错误:列表索引超出范围
IndexError: list index out of range
ID: python/indexerror-list-index-out-of-range
80%修复率
86%置信度
0证据数
2025-08-05首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.9 | active | — | — | — |
| 3.10 | active | — | — | — |
根因分析
访问列表中不存在的索引,例如长度为 3 的列表使用索引 5。
English
Accessing an index in a list that does not exist, e.g., list of length 3 with index 5.
解决方案
-
95% 成功率 Check list length before access
if len(my_list) > index: value = my_list[index]
-
90% 成功率 Use .get() equivalent for lists
value = my_list[index] if index < len(my_list) else None
无效尝试
常见但无效的做法:
-
Using try-except to ignore IndexError
70% 失败
Ignores the problem; test may pass incorrectly.
-
Using negative indexing blindly
50% 失败
Negative indexing may access unintended elements if list length changes.