IndexError: list index out of range and python

2019-01-02 16:08发布

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?

6条回答
临风纵饮
2楼-- · 2019-01-02 16:33

yes. sequence doesn't have the 54th item.

查看更多
永恒的永恒
3楼-- · 2019-01-02 16:36

The Way Python Indexing Works Is That It Starts At 0. So Your First Number Of Your List Would Be [0]. You Would Have to Print[52] as the first one is 0 and line 53 is [52].

Minus 1 And You Should be Fine :)

查看更多
流年柔荑漫光年
4楼-- · 2019-01-02 16:41

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

查看更多
低头抚发
5楼-- · 2019-01-02 16:43

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楼-- · 2019-01-02 16:47

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?

查看更多
骚的不知所云
7楼-- · 2019-01-02 16:53

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.

keep coding...

查看更多
登录 后发表回答