Python切片索引越界行为解析:字符串与数组的区别

宋时安
宋时安
发布时间:2026-10-16 | 4人浏览过
原创

本文探讨Python中切片操作在索引越界时的行为。测试表明,字符串切片越界不报错且可能复用原内存地址,而数组切片始终创建新对象。通过对比字符串与列表的切片结果及物理地址,解析Python对这两种数据类型的优化机制及空值返回规则。

前言

在处理Python字符串或数组数据时,切片是常用操作。例如在Leetcode_5等场景中。学习官方解法时注意到,Python允许切片索引超出序列最大索引值,且不会抛出编译器错误。本文旨在通过简单测试分析这一现象的具体表现,欢迎技术专家在评论区补充深层原理。

实例代码


a = '123'
b = a[:5]
print(b)

测试结果显示,即使切片索引超出范围,程序仍输出预期结果123且无报错。但若直接使用越界索引如a[5]访问单个元素,则会触发string index out of range错误。具体测试结果如下所示。

测试代码(字符串)


a = "1234567890"
a1 = a[:]
a2 = a[:len(a)]
a3 = a[:15]
a4 = a[16:16]
a5 = a[:2]

运行结果:

This is the id of 'a' : 2707772994160 This is the type of 'a' : <class 'str'> This is the value of 'a' : 1234567890

This is the id of 'a1' : 2707772994160 This is the type of 'a1' : <class 'str'> This is the value of 'a1' : 1234567890

This is the id of 'a2' : 2707772994160 This is the type of 'a2' : <class 'str'> This is the value of 'a2' : 1234567890

This is the id of 'a3' : 2707772994160 This is the type of 'a3' : <class 'str'> This is the value of 'a3' : 1234567890

This is the id of 'a4' : 2707740774832 This is the type of 'a4' : <class 'str'> This is the value of 'a4' :

This is the id of 'a5' : 2707773122544 This is the type of 'a5' : <class 'str'> This is the value of 'a5' : 12

值得注意的地方:

  • 当切片结果与原字符串内容完全一致时,新字符串变量指向的物理内存地址与原字符串相同(如a1、a2、a3的情况)。
  • 若切片结果与原字符串内容不同,Python会分配新的物理内存地址给新字符串(如a5的情况)。
  • 当切片索引范围内不包含任何合法字符时,返回对应类型的空值(如a4返回空字符串)。

测试代码(数组)


b = [1, 2, 3, 4, 5]
b1 = b[:]
b2 = b[:len(b)]
b3 = b[:15]
b4 = b[16:16]
b5 = b[:2]

This is the id of 'b' : 2260784433096 This is the type of 'b' : <class 'list'> This is the value of 'b' : [1, 2, 3, 4, 5]

This is the id of 'b1' : 2260784432456 This is the type of 'b1' : <class 'list'> This is the value of 'b1' : [1, 2, 3, 4, 5]

This is the id of 'b2' : 2260784470920 This is the type of 'b2' : <class 'list'> This is the value of 'b2' : [1, 2, 3, 4, 5]

This is the id of 'b3' : 2260784534280 This is the type of 'b3' : <class 'list'> This is the value of 'b3' : [1, 2, 3, 4, 5]

This is the id of 'b4' : 2260784471432 This is the type of 'b4' : <class 'list'> This is the value of 'b4' : []

This is the id of 'b5' : 2260784231944 This is the type of 'b5' : <class 'list'> This is the value of 'b5' : [1, 2]

值得注意的地方:

  • 数组(列表)的切片操作始终会创建新的物理内存地址,即使内容与原数组完全相同(如b1、b2、b3的地址均不同于b)。
  • 若切片索引范围内不存在合法数值,则返回相应类型的空列表(如b4返回[])。

到此这篇关于Python 切片索引越界的实现(数组下标越界)的文章就介绍到这了,更多相关Python 切片索引越界内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表