列出 remove() 方法
remove() 方法用於刪除給定元素的第一次出現,該方法使用此列表(我們必須從中刪除元素的列表)調用,並接受要刪除的元素作為參數。
用法:
list_name.remove(element)
參數:
element
– 它代表要刪除的元素。
返回值:
這個方法的返回類型是<class 'NoneType'>
,它什麽都不返回。
範例1:
# Python List remove() Method with Example
# declaring the list
cars = ["BMW", "Porsche", "Audi", "Lexus", "Audi"]
# printing the list
print("cars before remove operations...")
print("cars:", cars)
# removing "BMW"
cars.remove("BMW")
# removing "Audi"
cars.remove("Audi")
# printing the list
print("cars after remove operations...")
print("cars:", cars)
輸出
cars before remove operations... cars: ['BMW', 'Porsche', 'Audi', 'Lexus', 'Audi'] cars after remove operations... cars: ['Porsche', 'Lexus', 'Audi']
注意:如果列表中不存在任何元素,則方法返回 "ValueError"。
範例2:
# Python List remove() Method with Example
# declaring the list
x = [10, 20, 30, 40, 50, 60, 70]
# printing the list
print("x before remove operations...")
print("x:", x)
x.remove(10) # will remove 10
x.remove(70) # will remove 70
# printing the list
print("x after remove operations...")
print("x:", x)
# removing an element that doesn't exist
# in the list...
x.remove(100) # will generate error
輸出
x before remove operations... x: [10, 20, 30, 40, 50, 60, 70] x after remove operations... x: [20, 30, 40, 50, 60] Traceback (most recent call last): File "main.py", line 19, in <module> x.remove(100) # will generate error ValueError:list.remove(x):x not in list
相關用法
- Python List reverse()用法及代碼示例
- Python List clear()用法及代碼示例
- Python List pop()用法及代碼示例
- Python List index()用法及代碼示例
- Python List sort()用法及代碼示例
- Python List count()用法及代碼示例
- Python List copy()用法及代碼示例
- Python List extend()用法及代碼示例
- Python Lock acquire()用法及代碼示例
- Python Lock release()用法及代碼示例
- Python Lock locked()用法及代碼示例
- Python numpy.less()用法及代碼示例
- Python Sympy Permutation.list()用法及代碼示例
- Python Matplotlib.figure.Figure.subplots_adjust()用法及代碼示例
- Python numpy.tril()用法及代碼示例
- Python Matplotlib.pyplot.matshow()用法及代碼示例
- Python __file__用法及代碼示例
- Python Pandas Panel.add()用法及代碼示例
- Python Matplotlib.axis.Tick.get_window_extent()用法及代碼示例
- Python numpy.fromstring()用法及代碼示例
注:本文由純淨天空篩選整理自 Python List remove() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。