remove()是Python編程語言中的內置函數,可從列表中刪除給定的對象。它不返回任何值。
用法:
list_name.remove(obj)
參數:
obj - object to be removed from the list
返回值:
The method does not return any value but removes the given object from the list.
注意:它從列表中刪除該對象的第一個匹配項。
代碼#1:
# Python3 program to demonstrate the use of
# remove() method
# the first occurrence of 1 is removed from the list
list1 = [ 1, 2, 1, 1, 4, 5 ]
list1.remove(1)
print(list1)
# removes 'a' from list2
list2 = [ 'a', 'b', 'c', 'd' ]
list2.remove('a')
print(list2)
輸出:
[2, 1, 1, 4, 5] ['b', 'c', 'd']
錯誤:
It returns ValueError when the passed object is not present in the list
代碼#2:
# Python3 program for the error in
# remove() method
# removes 'e' from list2
list2 = [ 'a', 'b', 'c', 'd' ]
list2.remove('e')
print(list2)
輸出:
Traceback (most recent call last): File "/home/e35b642d8d5c06d24e9b31c7e7b9a7fa.py", line 8, in list2.remove('e') ValueError:list.remove(x):x not in list
實際應用:
給定一個列表,從列表中刪除所有1,然後打印列表。
代碼#3:
# Python3 program for practical application
# of removing 1 untill all 1 are removed from the list
list1 = [1, 2, 3, 4, 1, 1, 1, 4, 5]
# looping till all 1's are removed
while (list1.count(1)):
list1.remove(1)
print(list1)
輸出:
[2, 3, 4, 4, 5]
注:本文由純淨天空篩選整理自Striver大神的英文原創作品 Python list remove()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。