IndexError: list index out of range and python

爷,独闯天下 提交于 2019-11-26 00:44:29

问题


I\'m telling my program to print out line 53 of an output. Is this error telling me that there aren\'t that many lines and therefore can not print it out?


回答1:


If you have a list with 53 items, the last one is thelist[52] because indexing start at 0.




回答2:


Yes,

You are trying to access an element of the list that does not exist.

MyList = ["item1", "item2"]
print MyList[0] # Will work
print MyList[1] # Will Work
print MyList[2] # Will crash.

Have you got an off-by-one error?




回答3:


Yes. The sequence doesn't have the 54th item.




回答4:


The way Python indexing works is that it starts at 0, so the first number of your list would be [0]. You would have to print[52], as the starting index is 0 and therefore line 53 is [52].

Subtract 1 from the value and you should be fine. :)




回答5:


That's right. 'list index out of range' most likely means you are referring to n-th element of the list, while the length of the list is smaller than n.




回答6:


Always keep in mind when you want to overcome this error, the default value of indexing and range starts from 0, so if total items is 100 then l[99] and range(99) will give you access up to the last element.

whenever you get this type of error please cross check with items that comes between/middle in range, and insure that their index is not last if you get output then you have made perfect error that mentioned above.




回答7:


If you read a list from text file, you may get the last empty line as a list element. You can get rid of it like this:

list.pop()
for i in list:
   i[12]=....


来源:https://stackoverflow.com/questions/1098643/indexerror-list-index-out-of-range-and-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!