Python pop() - List 取出元素
pop() 方法用來移除並回傳指定位置的元素。
基本用法
fruits = ["apple", "banana", "orange"]
removed = fruits.pop()
print(removed) # orange
print(fruits) # ['apple', 'banana']
語法
list.pop(index=-1)
index:要移除的位置索引,預設為 -1(最後一個)- 回傳:被移除的元素
- 例外:空 list 或索引超出範圍時拋出 IndexError
移除指定位置的元素
fruits = ["apple", "banana", "orange", "grape"]
# 移除最後一個(預設)
last = fruits.pop()
print(last) # grape
print(fruits) # ['apple', 'banana', 'orange']
# 移除第一個
first = fruits.pop(0)
print(first) # apple
print(fruits) # ['banana', 'orange']
# 移除指定位置
middle = fruits.pop(0)
print(middle) # banana
print(fruits) # ['orange']
負數索引
numbers = [1, 2, 3, 4, 5]
print(numbers.pop(-1)) # 5(最後一個)
print(numbers) # [1, 2, 3, 4]
print(numbers.pop(-2)) # 3(倒數第二個)
print(numbers) # [1, 2, 4]
索引超出範圍
numbers = [1, 2, 3]
# 會拋出 IndexError
# numbers.pop(10) # IndexError: pop index out of range
# 空 list 也會報錯
empty = []
# empty.pop() # IndexError: pop from empty list
# 安全的做法
if numbers:
item = numbers.pop()
pop() vs remove()
fruits = ["apple", "banana", "orange"]
# pop() - 依索引移除,回傳被移除的元素
removed = fruits.pop(1)
print(removed) # banana
# remove() - 依值移除,不回傳
fruits = ["apple", "banana", "orange"]
fruits.remove("banana") # 回傳 None
實際範例
實作堆疊(Stack)
stack = []
# Push
stack.append("first")
stack.append("second")
stack.append("third")
# Pop(後進先出)
print(stack.pop()) # third
print(stack.pop()) # second
print(stack.pop()) # first
實作佇列(Queue)
queue = []
# Enqueue
queue.append("first")
queue.append("second")
queue.append("third")
# Dequeue(先進先出)
print(queue.pop(0)) # first
print(queue.pop(0)) # second
print(queue.pop(0)) # third
如果需要高效的佇列操作,建議使用
collections.deque。處理待辦事項
tasks = ["task1", "task2", "task3"]
while tasks:
current = tasks.pop(0)
print(f"Processing: {current}")
# 處理任務...
撤銷操作
actions = []
undo_stack = []
def do_action(action):
actions.append(action)
undo_stack.append(action)
print(f"Did: {action}")
def undo():
if undo_stack:
action = undo_stack.pop()
print(f"Undid: {action}")
else:
print("Nothing to undo")
do_action("Type A")
do_action("Type B")
do_action("Type C")
undo() # Undid: Type C
undo() # Undid: Type B
輪流處理
players = ["Alice", "Bob", "Charlie"]
# 輪流取出並放回末尾
for _ in range(6):
current = players.pop(0)
print(f"{current}'s turn")
players.append(current)
分離奇偶數
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = []
# 倒序處理避免索引問題
for i in range(len(numbers) - 1, -1, -1):
if numbers[i] % 2 == 0:
evens.append(numbers.pop(i))
evens.reverse()
print(f"Odds: {numbers}") # Odds: [1, 3, 5, 7, 9]
print(f"Evens: {evens}") # Evens: [2, 4, 6, 8, 10]
時間複雜度
pop()(末尾):O(1)pop(0)(開頭):O(n)pop(i)(中間):O(n)
如果需要頻繁從開頭移除元素,使用 collections.deque:
from collections import deque
d = deque([1, 2, 3, 4, 5])
d.popleft() # O(1)
print(list(d)) # [2, 3, 4, 5]