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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
