Python索引超出列表切片范围 [英] Python index out of range in list slicing

查看:218
本文介绍了Python索引超出列表切片范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然此代码将引发indexError:

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?

推荐答案

当您访问列表中元素的索引超出其长度时,我们将无法返回任何内容. (我们无法代表一个不存在的元素).这就是引发错误的原因.但是,在切片时,您要对原始列表进行切片 COPY ,如果起始或结尾无效,则新列表可以为空.

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.

这篇关于Python索引超出列表切片范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆