list.pop() 是 Python 列表中唯一同時修改列表並返回元素的方法,這一特性使其成為棧、隊列、狀態機實現的核心工具。本文全面解析其參數、返回值、異常行為、效能特性與進階用法。
element = list.pop([index])
-1 (最後一個元素)IndexError: pop from empty list (空列表) 或 IndexError: pop index out of range (索引越界)
stack = [1, 2, 3]
top = stack.pop() # 3, stack=[1,2]
first = stack.pop(0) # 1, stack=[2] (隊列出隊,但 O(n))
last = stack.pop(-1) # 2, stack=[] (同 pop())
stack = []
stack.append('a')
stack.append('b')
while stack:
item = stack.pop() # 獲取並移除
process(item)
tasks = ['email', 'report', 'meeting', 'backup']
# 處理最後一個緊急任務
if tasks and 'urgent' in tasks[-1]:
urgent_task = tasks.pop()
handle_urgent(urgent_task)
a = [1, 2, 3]
b = [4, 5, 6]
a.append(b.pop()) # a=[1,2,3,6], b=[4,5]
b.append(a.pop(0)) # b=[4,5,1], a=[2,3,6]
def safe_pop(lst, index=-1, default=None):
try:
return lst.pop(index)
except IndexError:
return default
# 或使用切片 (不修改原列表)
last = lst[-1:] and lst.pop() # 短路求值技巧
| 操作 | 時間複雜度 | 說明 |
|---|---|---|
pop() / pop(-1) | O(1) 平均 | 末尾刪除,無需移動元素 |
pop(0) | O(n) | 頭部刪除,需移動所有後續元素 |
pop(i) | O(n-i) | 中間刪除,移動後續元素 |
from collections import deque
q = deque([1,2,3])
q.popleft() # O(1) 真正常數時間
lst = ['a', 'b', 'c', 'd']
lst.pop(-1) # 'd' (最後)
lst.pop(-2) # 'c' (倒數第二)
lst.pop(-len(lst)) # 等同 pop(0)
# pop(-len(lst)-1) # IndexError
class CustomList:
def __init__(self, data):
self._data = list(data)
def pop(self, index=-1):
# 支援切片索引
if isinstance(index, slice):
return [self._data.pop(i) for i in range(*index.indices(len(self._data)))]
return self._data.pop(index)
def __repr__(self):
return repr(self._data)
cl = CustomList([1,2,3,4,5])
print(cl.pop(slice(1,3))) # [2, 3], cl=[1,4,5]
for x in lst: lst.pop() 導致索引錯亂 → 收集索引後反向刪除或用列表推導式過濾def f(lst=[]): lst.pop() 默認列表跨調用共享 → 用 None 做哨兵if lst: 或捕獲 IndexError| 方法 | 返回值 | 按值/索引 | 刪除數量 | 典型用途 |
|---|---|---|---|---|
pop(i) | 被刪元素 | 索引 | 1 | 棧、已知位置刪除 |
remove(x) | None | 值 (首個匹配) | 1 | 按值刪除 |
del lst[i] | None | 索引/切片 | 1 或多 | 切片刪除、無需返回值 |
lst.clear() | None | 全部 | 所有 | 清空列表 |
善用 pop() 的返回值特性,能寫出更緊湊、更具表達力的狀態操作代碼,是 Python 列表操作的核心技巧之一。