Python 列表切片语法
在 Python 中,我们可以使用 “切片” 的方式来截取列表的某一部分。
语法:
list[m:n:step]说明:
其中,m 是开始下标,n 是结束下标,step 是步长(默认值为 1)。很多情况下情况下,step 都是缺省(即采用默认值 1)。
m 和 n 可以是正数,也可以是负数,不过 n 一定要大于 m。list[m:n] 的截取范围为 [m, n),也就是包含 m 不包含 n。其中 m 和 n 都可以省略。
- 当 n 省略时,获取的范围为:m 到结尾位置。
- 当 m 省略时,获取的范围为:开头位置到 n。
- 当 m 和 n 同时省略,获取范围为:整个列表。
提示: 字符串也有切片的语法,另请参阅:Python 字符串切片。
Python 列表切片示例
接下来,我们通过几个简单的例子来讲解 Python 列表切片是如何使用的。
示例 1:列表正向切片
animals = ['ant', 'bee', 'cat', 'dog', 'ewe']
print(animals[0:3])
print(animals[2:5])运行结果如下。
['ant', 'bee', 'cat']
['cat', 'dog', 'ewe']分析:
对于上面的示例来说,具体分析如下图所示。

示例 2:列表反向切片
animals = ['ant', 'bee', 'cat', 'dog', 'ewe']
print(animals[-3:-1])
print(animals[-5:-2])运行结果如下。
['cat', 'dog']
['ant', 'bee', 'cat']分析:
对于上面的示例来说,具体分析如下图所示。

示例 3:list[m:]
animals = ['ant', 'bee', 'cat', 'dog', 'ewe']
print(animals[2:])
print(animals[-2:])运行结果如下。
['cat', 'dog', 'ewe']
['dog', 'ewe']分析:
对于上面的示例来说,具体分析如下图所示。

示例 4:list[:n]
animals = ['ant', 'bee', 'cat', 'dog', 'ewe']
print(animals[:2])
print(animals[:-2])运行结果如下。
['ant', 'bee']
['ant', 'bee', 'cat']分析:
对于上面的示例来说,具体分析如下图所示所示。

示例 5:list[:]
animals = ['ant', 'bee', 'cat', 'dog', 'ewe']
print(animals[:])
print(animals[:] == animals)运行结果如下。
['ant', 'bee', 'cat', 'dog', 'ewe']
True分析:
[:] 表示 m 和 n 都省略,此时 list[:] 返回的就是列表本身。
提示: list[:] 这种切片方式可以用于复制一个列表,这是一个很实用的技巧。
示例 6:list[m:n] 和 list[n]
animals = ['ant', 'bee', 'cat', 'dog', 'ewe']
part = animals[0:1]
item = animals[0]
print(type(part))
print(type(item))运行结果如下。
<class 'list'>
<class 'str'>分析:
需要注意一点,list[m:n] 返回的结果是一个列表,而 list[m] 返回的结果是一个元素。在这个例子中,animals[0:1] 返回的结果是 ['ant'],animals[0] 返回的结果是 'ant'。虽然 ['ant'] 只有一个元素,但它依然是一个列表。
示例 7:带步长的列表切片
animals = ['ant', 'bee', 'cat', 'dog', 'ewe']
# 步长为 2
print(animals[0:4:2])
# 步长为 -1
print(animals[::-1])运行结果如下。
['ant', 'cat']
['ewe', 'dog', 'cat', 'bee', 'ant']分析:
animals[0:4:2] 的步长为 2,表示每隔 1 个元素取一个。animals[::-1] 的步长为 -1,这是一个非常经典的技巧,用于反转列表。
列表切片的技巧
最后,给小伙伴们总结一下列表切片的技巧,如下表所示。
| 切片 | 说明 |
|---|---|
| list[:] | 截取所有元素 |
| list[:n] | 截取开头 n 个元素 |
| list[n:] | 截取从 list[n] 开始到结尾 |
| list[-n:] | 截取末尾 n 个元素 |
| list[m:n] | 截取范围为 [m, n) |
| list[::-1] | 反转列表 |
