list.remove(x) 從列表中移除第一個等於 x 的元素,不返回值,僅原地修改。本文詳細說明其行為、異常處理、與 pop()/del 的本質區別及最佳實踐。
lst = [1, 2, 3, 2, 4]
lst.remove(2) # 移除首個 2
print(lst) # [1, 3, 2, 4]
lst.remove(2) # 移除下一個 2
print(lst) # [1, 3, 4]
# lst.remove(99) # ValueError: list.remove(x): x not in list
== 比較)NoneValueError 若值不存在
if value in lst:
lst.remove(value)
try:
lst.remove(value)
except ValueError:
pass # 或記錄日誌
# 利用短路求值 (不推薦,可讀性差)
value in lst and lst.remove(value)
# 推薦:封裝函數
def safe_remove(lst, value):
try:
lst.remove(value)
except ValueError:
return False
return True
| 操作 | 定位方式 | 返回值 | 刪除數量 | 異常類型 | 典型場景 |
|---|---|---|---|---|---|
remove(x) | 值 (首個匹配) | None | 1 | ValueError | 按內容刪除 |
pop(i) | 索引 (預設 -1) | 被刪元素 | 1 | IndexError | 棧、已知位置 |
del lst[i] | 索引/切片 | None | 1 或多 | IndexError | 切片刪除、無需返回 |
lst.clear() | 全部 | None | 所有 | 無 | 清空列表 |
# 方法 1: 列表推導式 (建立新列表)
lst = [x for x in lst if x != value]
# 方法 2: 反向遍歷索引刪除 (原地修改)
for i in range(len(lst)-1, -1, -1):
if lst[i] == value:
del lst[i]
# 方法 3: while 循環 (原地)
while value in lst:
lst.remove(value)
# 按屬性移除
class Item:
def __init__(self, id, name):
self.id, self.name = id, name
items = [Item(1,'a'), Item(2,'b'), Item(1,'c')]
target_id = 1
# 反向遍歷安全刪除
for i in range(len(items)-1, -1, -1):
if items[i].id == target_id:
del items[i]
# items = [Item(2,'b')]
remove(x):O(n) 查找 + O(n) 移動 = O(n)set 或 dict (O(1) 查找)collections.OrderedDict 或第三方 blist/banyan
# 陷阱 1: 迭代中 remove
lst = [1, 2, 3, 2, 4]
for x in lst:
if x == 2:
lst.remove(x) # 跳過元素!輸出 [1, 3, 2, 4]
# 正確:反向索引或建立新列表
lst = [x for x in lst if x != 2]
# 陷阱 2: 可變對象身份 vs 相等
a = [1,2]
b = [1,2]
lst = [a]
lst.remove(b) # 成功!因為 a == b (列表按值比較)
# 但若為自定義類未實現 __eq__,則比較身份 (is)
remove() = 「按值刪除首個」+ 「無返回值」+ 「缺失拋異常」try/except 實現 EAFP 風格精通列表修改三劍客 (pop/remove/del) 的語義邊界,是寫出正確、高效 Python 代碼的基本功。