在 Python 中列表上的 del、remove 和 pop 有什麼區別?


程式碼行數並不重要。在 Python 列表中刪除元素時,你需要考慮 removedelpop 在 Python 列表中的區別以及使用哪一個

remove:remove() 刪除第一個匹配的值或物件,而不是特定索引。例如 list.remove(value)

示例

list=[10,20,30,40]
list.remove(30)
print(list)

輸出

[10, 20, 40]


del:del 刪除特定索引處的元素。例如 del list[index]

示例

list = [10,20,30,40,55]
del list[1]
print(list)

輸出

[10, 30, 40, 55]


pop:pop 刪除特定索引處的元素並返回它。例如 list.pop(index)

示例

list = [100, 300, 400,550]
list.pop(1)
print(list)

輸出

[100, 400, 550]

更新於:30-7-2019

470 次瀏覽

開啟你的職業生涯

完成課程並取得認證

開始
廣告
© . All rights reserved.