How can I ignore ValueError when I try to remove an element from a list?

How can I ignore the "not in list" error message if I call a.remove(x) when x is not present in list a?

This is my situation:

>>> a = range(10)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a.remove(10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> a.remove(9)
88887 次浏览

一个很好的线程安全的方法就是尝试一下,忽略异常:

try:
a.remove(10)
except ValueError:
pass  # do nothing!

我个人会考虑使用 set而不是 list,只要元素的顺序不一定重要。然后你可以使用丢弃的方法:

>>> S = set(range(10))
>>> S
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> S.remove(10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 10
>>> S.discard(10)
>>> S
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

作为忽略 ValueError的替代方案

try:
a.remove(10)
except ValueError:
pass  # do nothing!

I think the following is a little more straightforward and readable:

if 10 in a:
a.remove(10)

更好的办法是

source_list = list(filter(lambda x: x != element_to_remove,source_list))

Because in a more complex program, the exception of ValueError could also be raised for something else and a few answers here just pass it, thus discarding it while creating more possible problems down the line.

你输入了错误的输入。 语法: list.remove (x)

X 是列表中的元素。 in remove parenthesis ENTER what already have in your list. 删除(2)

我输入了2,因为它在列表中。 我希望这些数据能帮到你。

列表内涵怎么样?

a = [x for x in a if x != 10]

When I only care to ensure the entry is not in a list, dict, or set I use contextlib like so:

import contextlib


some_list = []
with contextlib.suppress(ValueError):
some_list.remove(10)


some_set = set()
some_dict = dict()
with contextlib.suppress(KeyError):
some_set.remove('some_value')
del some_dict['some_key']

我认为最简单的方法(可能不是最好的方法)是写下如果语句检查这个值是否在列表中,然后从列表中删除它。

if 10 in a:
a.remove(10)