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

本文介绍了Python列表的remove()方法,用于移除列表中首次出现的指定元素。方法接受一个参数,即要删除的元素,并在元素不存在时抛出'ValueError'。文中给出了两个示例来演示其用法。
摘要由CSDN通过智能技术生成

python 示例

列出remove()方法 (List remove() Method)

remove() method is used to remove the first occurrence of the given element, the method is called with this list (the list from which we have to remove the element) and accepts the element to be removed as an argument.

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

Syntax:

句法:

    list_name.remove(element)

Parameter(s):

参数:

  • element – It represents the element to be removed.

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

Return value:

返回值:

The return type of this method is <class 'NoneType'>, it returns nothing.

此方法的返回类型为<class'NoneType'> ,它什么也不返回。

Example 1:

范例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)

Output

输出量

cars before remove operations...
cars:  ['BMW', 'Porsche', 'Audi', 'Lexus', 'Audi']
cars after remove operations...
cars:  ['Porsche', 'Lexus', 'Audi']

Note: If any element doesn't exist in the list, method returns "ValueError".

注意:如果列表中不存在任何元素,则方法返回“ ValueError”。

Example 2:

范例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

Output

输出量

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


翻译自: https://www.includehelp.com/python/list-remove-method-with-example.aspx

python 示例

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值