目录
描述
list.remove()方法删除列表中指定值的元素。常用在不确定或不关心元素在列表中的位置的场景中。
语法和参数
list.remove(object)
| 名称 | 含义 | 备注 |
| object | 列表中要移除的元素 | 不可省略的参数 |
返回值
None
使用示例
>>> demo = [1, 3, 5]
>>> demo.remove(5)
>>> demo
[1, 3]
注意事项
删除不存在的元素
当删除一个列表中不存在的元素时,Python抛出ValueError异常。
>>> demo = [1, 3, 5]
>>> demo.remove(6)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
要删除的元素在列表中存在多个
当要删除的元素在列表中存在多个时,remove()方法删除位置最靠前的一个匹配元素。
demo = ["Pod", "ReplicationController", "Namespace", "ReplicationController"]
demo.remove("ReplicationController")
print(demo)
# outputs:
# ['Pod', 'Namespace', 'ReplicationController']

Python的list.remove()方法用于删除列表中指定值的第一个出现,如果元素不存在则会抛出ValueError。若元素存在多个,只会删除第一个。
7万+

被折叠的 条评论
为什么被折叠?



