尝试访问第N';个项目时,&Quot;IndexError:列表索引超出范围是否意味着我的列表少于N个项目? [英] Does "IndexError: list index out of range" when trying to access the N'th item mean that my list has less than N items?
本文介绍了尝试访问第N';个项目时,&Quot;IndexError:列表索引超出范围是否意味着我的列表少于N个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
推荐答案
如果您有一个包含53个项目的列表,则最后一个项目是thelist[52]
,因为索引从0开始。
发件人Real Python: Understanding the Python Traceback - IndexError
:
IndexError
当您尝试从序列(如
list
或tuple
)检索索引时,会引发IndexError
,但在序列中找不到该索引。Python文档定义了何时引发此异常:在序列下标超出范围时引发。(Source)
这里有一个引发
的示例IndexError
:test = list(range(53)) test[53] --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-6-7879607f7f36> in <module> 1 test = list(range(53)) ----> 2 test[53] IndexError: list index out of range
IndexError
的错误消息行没有为您提供大量信息。您可以看到,您有一个out of range
序列引用,以及序列的类型是什么,在本例中是list
。这些信息结合回溯的睡觉通常足以帮助您快速确定如何解决该问题。这篇关于尝试访问第N';个项目时,&Quot;IndexError:列表索引超出范围是否意味着我的列表少于N个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文