python - 尝试访问第 N 个项目时出现 "IndexError: list index out of range"是否意味着我的列表中的项目少于 N 个?

标签 python list index-error

我告诉我的程序打印输出的第 53 行。这个错误是否告诉我没有那么多行,因此无法打印出来?

最佳答案

如果您有一个包含 53 个项目的列表,则最后一个是 thelist[52],因为索引从 0 开始。


来自 Real Python: Understanding the Python Traceback - IndexError :

IndexError

The IndexError is raised when you attempt to retrieve an index from a sequence, like a list or a tuple, and the index isn’t found in the sequence. The Python documentation defines when this exception is raised:

Raised when a sequence subscript is out of range. (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

The error message line for an IndexError doesn’t give you great information. You can see that you have a sequence reference that is out of range and what the type of the sequence is, a list in this case. That information, combined with the rest of the traceback, is usually enough to help you quickly identify how to fix the issue.

关于python - 尝试访问第 N 个项目时出现 "IndexError: list index out of range"是否意味着我的列表中的项目少于 N 个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1098643/

相关文章:

从 shell 调用 python 脚本时不执行

python - 自动评分器脚本 - 从文本文件读取键盘输入

python - 导入 Tensorflow 有效但不导入任何内容

java - 我正确使用 list.remove 吗?

python - iCal 库可迭代特定实例的重复事件

c++ - 使用 std::list 作为循环列表是否安全?

Java Lists 列表项值

python - PyQt5:为pandas表模型实现removeRows

arrays - 沿第二轴连接2个1D`numpy`数组

python - 可视化特征图: IndexError: too many indices for array