简体   繁体   English

列表索引超出范围

[英]list index out of range

how is this possible, I have a list called "temp". 这怎么可能,我有一个名为“ temp”的列表。 This is what I have in my python interpreter. 这就是我的python解释器中的内容。

In [150]: len(temp)
Out[150]: 773942

In [151]: temp[773942]

and I get an IndexError: list index out of range. 我得到一个IndexError:列表索引超出范围。

I'm confused because it just told me that there are 773942 values in the list, and now it tells me that the index is out of range? 我很困惑,因为它只是告诉我列表中有773942个值,现在它告诉我索引超出范围了?

The indices of a list are in the range from 0 to len(temp) - 1 . 列表的索引在0len(temp) - 1的范围内。 Your index is one past the end. 您的索引是最后的索引。

For example a list of length three has the following indices: 例如,长度为三的列表具有以下索引:

["a",   "b",   "c"]
 ^      ^      ^
 0      1      2

Accessing index 3 would be one past the end. 访问索引3将是末尾的索引。

索引是从零开始的,所以最后一个元素是len()-1

In python len() returns how many elements there are in your list. 在python中, len()返回列表中有多少个元素。 However indexes start at 0. So for example: 但是索引从0开始。因此例如:

>>>a = [1,2,3]
>>>len(a)
3
>>>a[0]
1
>>>a[2]
3

So this maximum index of python list is len(list) - 1 otherwise error is raised. 因此,python list最大索引为len(list) - 1否则将引发错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM