如何在Python中刪除列表中的物件?
要從Python中的列表中刪除專案(元素),可以使用列表函式clear()、pop()和remove()。您還可以使用del語句透過指定帶有索引或切片的位置或範圍來刪除專案。
在本文中,我們將向您展示如何使用Python從列表中刪除物件/元素。以下是完成此任務的4種不同方法:
使用remove()方法
使用del關鍵字
使用pop()方法
使用clear()方法
假設我們已經建立了一個包含一些元素的列表。我們將使用上面指定的不同方法,在刪除輸入列表中的給定專案後返回結果列表。
方法1:使用remove()方法
remove()函式刪除作為引數傳遞給它的給定專案。
語法
list.remove(element) Return Value:The remove() function will not return any value(returns None)
演算法(步驟)
以下是執行所需任務的演算法/步驟
建立一個變數來儲存輸入列表。
使用remove()方法透過將要刪除的列表項作為引數傳遞給它並將其應用於輸入列表來刪除輸入列表中的特定項。
列印刪除指定項後的結果列表
示例
以下程式使用remove()方法從輸入列表中刪除指定項並列印結果列表:
# input list inputList = ['TutorialsPoint', 'Python', 'Codes', 'hello', 'everyone'] # Removing the 'TutorialsPoint' from the list using the remove() method inputList.remove("TutorialsPoint") # Printing the result list print("Input List after removing {TutorialsPoint}:\n", inputList)
輸出
執行上述程式將生成以下輸出:
Input List after removing {TutorialsPoint}: ['Python', 'Codes', 'hello', 'everyone']
作為程式碼的輸入,我們得到一個包含一些隨機值的示例列表,以及要從列表中刪除的物件/元素。然後將該元素傳遞給remove()方法,在該方法中將其從列表中刪除/移除。如果列表中找不到物件/元素,則會返回ValueError。
方法2:使用del關鍵字
del語句不是列表函式。del語句可用於透過傳遞要刪除的項(元素)的索引來刪除列表中的項。
演算法(步驟)
以下是執行所需任務的演算法/步驟:
建立一個變數來儲存輸入列表。
使用del關鍵字刪除列表中指定索引(此處為第2個索引(程式碼))處的項。
列印結果列表,即刪除指定項後的列表。
示例
以下程式使用del關鍵字從輸入列表中刪除指定項並列印結果列表:
# input list inputList = ['TutorialsPoint', 'Python', 'Codes', 'hello', 'everyone'] # Removing the item present at the 2nd index(Codes) from the list del inputList[2] # Printing the result list print("Input List after removing the item present at the 2nd index{Codes}:\n", inputList)
輸出
執行上述程式將生成以下輸出:
Input List after removing the item present at the 2nd index{Codes}: ['TutorialsPoint', 'Python', 'hello', 'everyone']
方法3:使用pop()方法
使用pop()方法,您可以刪除指定位置的元素並檢索其值。
索引的起始值為0(基於零的索引)。
如果未指定索引,則pop()方法將刪除列表中的最後一個元素。
可以使用負值來表示從末尾開始的位置。最後一個索引是-1。
演算法(步驟)
以下是執行所需任務的演算法/步驟:
建立一個變數來儲存輸入列表。
使用pop()方法,將列表項的索引作為引數傳遞給它,以刪除給定索引處的項。
將負索引值作為引數傳遞給pop()方法,以從末尾刪除列表項。此處,為了從列表中刪除最後一項,我們將-1索引作為引數傳遞給pop()方法。
列印結果列表,即刪除指定項後的列表。
示例
以下程式使用pop()方法從輸入列表中刪除指定項並列印結果列表:
# input list inputList = ['TutorialsPoint', 'Python', 'Codes', 'hello', 'everyone'] # Removing the 'TutorialsPoint' from the list using the pop() method del_item = inputList.pop(0) # Removing the 'everyone' from the list by passing the negative index -1 last_del_item = inputList.pop(-1) # Printing the result list print("Input List after removing {TutorialsPoint}, {everyone}:\n", inputList)
輸出
Input List after removing {TutorialsPoint}, {everyone}: ['Python', 'Codes', 'hello']
方法4:使用clear()方法
clear()方法刪除列表中的所有項。列表仍然存在,但它是空的。
演算法(步驟)
以下是執行所需任務的演算法/步驟:
建立一個變數來儲存輸入列表。
使用clear()方法刪除列表中的所有項。
列印結果列表,即刪除所有項後的列表。
示例
以下程式使用clear()函式清除或清空整個列表:
# input list inputList = ['TutorialsPoint', 'Python', 'Codes', 'hello', 'everyone'] # Removing all the items from the list inputList.clear() # Printing the result list print("Input List after removing all the items:", inputList)
輸出
Input List after removing all the items: []
結論
在本文中,我們學習瞭如何使用四種不同的方法從列表中刪除物件/元素:remove()、pop()、clear()和del關鍵字。我們還學習瞭如果元素不在列表中,這些方法會生成的錯誤。