python列表remove()移除第一个匹配元素

列表remove()方法描述

python列表内置的方法remove()可以用来移除参数指定的列表元素,而且是移除第一个匹配到的列表元素,如果remove()方法无法在调用对象中查找到参数指定的元素,python则抛出ValueError。


列表remove()语法及参数结构

list.remove( obj )

参数obj为python对象object,指定remove()所要移除的列表元素。


列表remove()返回值

remove()方法没有返回值,但可以移除列表中的元素,列表会被修改。


列表remove()实例代码

>>> list1 = list(range(10))
>>> list1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list1.remove(9)
>>> list1
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> list1.remove(9) #当remove()移除列表中不存在的元素,python会抛出ValueError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> list2 = [1,1,1,1,1,1]
>>> list2.remove(1) #remove()移除第一个匹配到的元素。
>>> list2
[1, 1, 1, 1, 1]

全栈后端 / python教程 :


























Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.