Python index out of range in list slicing [duplica

2019-02-17 08:14发布

This question already has an answer here:

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?

2条回答
ら.Afraid
2楼-- · 2019-02-17 08:44

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

if sys.argv[2:]:
    # do something with sys.argv[2], knowing it exists
查看更多
Ridiculous、
3楼-- · 2019-02-17 08:45

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.

查看更多
登录 后发表回答