Python 的 list.pop(~) 方法从列表中删除给定索引处的元素,然后返回删除的值。
注意
当您想要从列表中删除元素,然后对删除的元素执行某些操作(例如将其添加到另一个列表)时,list.pop(~) 方法非常有用。
参数
1.index | number | optional
要删除的元素的索引位置。默认值为 -1 ,即列表中的最后一个元素。
返回值
删除的值。
例子
基本用法
要删除 fav_animals 的最后一个元素并返回它:
fav_animals = ['cat', 'doge', 'bird']
fav_animals.pop()
'bird'
要弹出 fav_animals 的第一个元素并将其添加到单独的列表 norm_animals 中:
fav_animals = ['cat', 'doge', 'bird']
norm_animals = []
norm_animals.append(fav_animals.pop(0))
print("fav_animals =", fav_animals)
print("norm_animals =", norm_animals)
fav_animals = ['doge', 'bird']
norm_animals = ['cat']
这里 'cat' 是从 fav_animals 中弹出的,然后用作  list.append(~)  方法的输入,将其添加到列表 norm_animals 中。
IndexError
如果要弹出的指定索引不存在,则会引发 IndexError:
fav_animals = ['cat', 'doge', 'bird']
fav_animals.pop(3)
IndexError: pop index out of range
相关用法
- Python List pop()用法及代码示例
 - Python List remove()用法及代码示例
 - Python List insert()用法及代码示例
 - Python List clear()用法及代码示例
 - Python List reverse()用法及代码示例
 - Python List copy方法用法及代码示例
 - Python List sort方法用法及代码示例
 - Python List extend方法用法及代码示例
 - Python List append()用法及代码示例
 - Python List cmp()用法及代码示例
 - Python List remove方法用法及代码示例
 - Python List append方法用法及代码示例
 - Python List index()用法及代码示例
 - Python List sort()用法及代码示例
 - Python List reverse方法用法及代码示例
 - Python List list()用法及代码示例
 - Python List max()用法及代码示例
 - Python List count()用法及代码示例
 - Python List insert方法用法及代码示例
 - Python List len()用法及代码示例
 - Python List count方法用法及代码示例
 - Python List min()用法及代码示例
 - Python List index方法用法及代码示例
 - Python List clear方法用法及代码示例
 - Python List copy()用法及代码示例
 
注:本文由纯净天空筛选整理自Isshin Inada大神的英文原创作品 Python List | pop method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
