列出 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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。