Python index out of range in list slicing [duplicate]

对着背影说爱祢 提交于 2019-12-01 01:55:02

问题


While this code will raise indexError:

In [1]: lst = [1, 2, 3]
In [2]: lst[3]
IndexError: list index out of range

Slicing the list with "out of range index" will not produce any error.

In [3]: lst[3:]
Out[3]: []

What is the rationale of this design?


回答1:


When you are accessing an element in a list whose index is beyond its length, we cannot return anything. (There is no way we can represent an element which is not there). That's why the error is thrown. But when you are slicing, you are making a sliced COPY of the original list and that new list can be empty if the start or end are not valid.




回答2:


It's nice being able to test if an element exists:

if sys.argv[2:]:
    # do something with sys.argv[2], knowing it exists


来源:https://stackoverflow.com/questions/20033201/python-index-out-of-range-in-list-slicing

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