带有示例的Python列表remove()方法

清单remove()方法

remove()方法用于删除给定元素的第一次出现,该方法用此列表(必须从中删除元素的列表)调用,并接受要删除的元素作为参数。

语法:

    list_name.remove(element)

Parameter(s):

  • element –它表示要删除的元素。

返回值:

此方法的返回类型为<class'NoneType'>,它不返回任何内容。

范例1:

# 带有示例的Python列表remove()方法

# 宣布名单
cars = ["BMW", "Porsche", "Audi", "Lexus", "Audi"]

# 打印清单
print("cars before remove operations...")
print("cars: ", cars)

# 删除“宝马”"BMW"
cars.remove("BMW")
# 删除“宝马”"Audi"
cars.remove("Audi")

# 打印清单 
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列表remove()方法

# 宣布名单
x = [10, 20, 30, 40, 50, 60, 70]

# 打印清单
print("x before remove operations...")
print("x: ", x)

x.remove(10)   # 将删除10
x.remove(70)   # 将删除70

# 打印清单
print("x after remove operations...")
print("x: ", x)

# 删除“宝马”an element that doesn't exist
# 在列表中...
x.remove(100) # 会产生错误

输出结果

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) # 会产生错误
ValueError: list.remove(x): x not in list