本文介绍如何处理报错–IndexError: list index out of range
源代码:
list1 = [1, 2, 3, 4]
print(list1[len(list1)])
运行报错如下:
Traceback (most recent call last):
File "D:/Program Files/PycharmProjects/pycharmPrj/zzz/Python/lx0.py", line 49, in <module>
print(list1[len(list1)])
IndexError: list index out of range
这里明显的是超出索引范围报错,len(list1)获取列表的长度是4,而列表索引是从0开始,list1列表最大索引值才到3,因此视图去访问索引一个不存在的值,肯定报错:IndexError: list index out of range