Python pop() 语法
pop() 是 Python 列表的一个方法,它用于删除列表中指定位置的元素。该方法会修改原列表,并且返回已删除的元素。
语法:
list.pop(index)说明:
index 是可选参数,表示下标位置(可以是负整数、0 或正整数),默认值为 -1。也就是说,如果 index 省略,则会使用 -1 作为参数,此时表示删除列表的最后一个元素。
提示:
- remove() 方法是根据 “值” 来删除元素,而 pop() 方法是根据 “下标” 来删除元素。
- 字典也有类似的 pop() 方法,另请参阅:Python 字典 pop() 方法。
Python pop() 摘要
| 使用频率 | 中 |
|---|---|
| 修改原列表 | 是 |
| 时间复杂度 | O(1)(删除末尾元素),O(n)(删除非末尾元素) |
| 官方文档 | 查看 |
Python pop() 示例
接下来,我们通过几个简单的例子来讲解一下 Python pop() 方法是如何使用的。
示例 1:pop() 传递参数
cities = ['北京', '上海', '广州', '深圳', '杭州']
result = cities.pop(2)
print(cities)
print(result)运行结果如下。
['北京', '上海', '深圳', '杭州']
广州分析:
cities.pop(2) 表示删除第 3 个元素,也就是 '广州'。
示例 2:pop() 不传递参数
cities = ['北京', '上海', '广州', '深圳', '杭州']
result = cities.pop()
print(cities)
print(result)运行结果如下。
['北京', '上海', '广州', '深圳']
杭州分析:
cities.pop() 等价于 cities.pop(-1),它表示删除最后一个元素,也就是 '杭州'。
示例 3:pop() 传递负索引
cities = ['北京', '上海', '广州', '深圳', '杭州']
result = cities.pop(-2)
print(cities)
print(result)运行结果如下。
['北京', '上海', '广州', '杭州']
深圳分析:
cities.pop(-2) 表示删除倒数第 2 个元素,即 '深圳'。
示例 4:pop() 索引越界
cities = ['北京', '上海', '广州', '深圳', '杭州']
result = cities.pop(5)
print(cities)
print(result)运行结果如下。
IndexError: pop index out of range分析:
列表 cities 的长度为 5,其索引最大值为 4(索引是从 0 开始)。
示例 5:空列表使用 pop()
cities = []
result = cities.pop()
print(cities)
print(result)运行结果如下。
IndexError: pop from empty list分析:
空列表无法执行 pop() 操作,建议配合条件判断来使用:if len(cities) > 0: cities.pop()。
del、pop() 和 remove()
对于删除操作,列表提供了 del、pop() 和 remove() 这几种方式。
- 如果希望根据 “下标” 来删除元素,应该使用 pop() 方法。
- 如果希望根据 “值” 来删除元素,应该使用 remove() 方法。
- 如果希望删除列表的一部分,应该使用 del 关键字。
示例 6:del vs pop() vs remove()
# pop()
nums1 = [10, 20, 30, 40, 50]
nums1.pop(1)
print(nums1)
# remove()
nums2 = [10, 20, 30, 40, 50]
nums2.remove(50)
print(nums2)
# del
nums3 = [10, 20, 30, 40, 50]
del nums3[0:2]
print(nums3)运行结果如下。
[10, 30, 40, 50]
[10, 20, 30, 40]
[30, 40, 50]