1)Python del函數 (1) Python del function)
del is nothing but "delete". del is a keyword which basically goes on the position given by the user in del(position) and deletes that element and also changes the positions of all the other elements as it is now not the part of the list.
del只是“刪除”而已。 del是一個關鍵字,它基本上位于用戶在del(position)中給定的位置上,并刪除該元素,并更改所有其他元素的位置,因為它現在不在列表中。
One import thing in delete is that it takes the argument in it is id i.e. not the whole data which is to be deleted only the location of the data.
delete中的一個重要事項是它接受參數中的id,即不是要刪除的整個數據,而是僅數據的位置。
2)Python移除功能 (2) Python remove function)
remove is nothing only the searching of the first occurrence of the element and removes that element.
remove只是搜索元素的第一次出現并刪除該元素。
Note: "remove" is slower than the "del" as it has to search the element which makes it slow.
注意: “刪除”比“ del”要慢,因為它必須搜索使其變慢的元素。
3)Python pop函數 (3) Python pop function)
The pop() only takes the single argument i.e the index and removes the element from there without affecting any others position. If we pass the index which was not in the range of the given list then it through the error i.e. "IndexError: pop index out of range".
pop()僅采用單個參數,即索引,并從那里刪除元素,而不會影響其他位置。 如果我們傳遞的索引不在給定列表的范圍內,則它會通過錯誤即“ IndexError:pop index out of range”出現錯誤。
It is not necessary to pass the argument in the pop function if not passed it takes it -1 by itself and remove the element from the last and delete that location from the list.
如果未傳遞參數,則無需在pop函數中傳遞參數,否則參數本身會使其為-1并從最后一個元素中刪除該元素,然后從列表中刪除該位置。
列表中del,remove和pop函數的Python示例 (Python example for del, remove and pop functions in the list)
l=[1,2,3,4,6,5,6,7,8,6] #list
# del deletes the 4th position element i.e 6
del(l[4])
#new list after deletion
print('After deletion:',l)
#removes the value 6 from list
l.remove(6)
# new list after removing
print('After removing:',l)
#pop of the element at location 1
l.pop(1)
# new list after pop
print('After pop:',l)
#pop of the element from the last of the list
l.pop(-3)
# new list after pop
print('After pop:',l)
#pop of the elements from the
l.pop()
# new list after pop
print('After pop:',l)
Output
輸出量
After deletion: [1, 2, 3, 4, 5, 6, 7, 8, 6]
After removing: [1, 2, 3, 4, 5, 7, 8, 6]
After pop: [1, 3, 4, 5, 7, 8, 6]
After pop: [1, 3, 4, 5, 8, 6]
After pop: [1, 3, 4, 5, 8]
Explanation of the code:
代碼說明:
In the above code,
del(l[4])
deletes the 4th position element i.e. 6 of the list,
and also change the position/location of all other further elements.
And,
l.remove(6)
Removes the element 6 from the list.
And, while using pop in list
l.pop(1)
Pops off the first element of the list .
And,
l.pop(-3)
Pops off the 3rd element from the last
that means negative value means from last
And,
l.pop( )
If not given any argument by default take that -1.
翻譯自: https://www.includehelp.com/python/difference-between-del-remove-and-pop-functions-of-a-list-in-python.aspx