成功解决BUG:IndexError: list index out of range
异常解读
在 Python 代码编写过程中,会出现如下错误:
IndexError: list index out of range
该错误翻译为中文是:
出错原因:当尝试访问列表中不存在的索引时,就会引发 IndexError。
解决思路
索引超出列表范围了,在下述这个例子中,我们尝试打印 my_list 中索引为 5 的元素。然而,my_list 只有 3 个元素,索引的范围是 0 到 2,因此索引 5 超出了列表的范围,会导致 IndexError。
错误复现
可以在 Python 文件中输入如下代码,即可出现本文标题所示错误:
my_list = [1, 2, 3]
try:
print(my_list[5])
except IndexError as e:
print(f"Caught an IndexError: {
e}")
错误信息如下
Caught an IndexError: list index out of range
其他学习资料
- 《滚雪球学Python》专栏与实体书:https://dream.blog.csdn.net/article/details/131268344
- 《爬虫100例》:https://blog.csdn.net/hihell/category_9280209.html
- 《Python爬虫120》:https://blog.csdn.net/hihell/category_11079529.html