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:
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']
As an alternative to ignoring the 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)
you have typed wrong input. syntax: list.remove(x)
and x is the element of your list. in remove parenthesis ENTER what already have in your list. ex: a.remove(2)
i have entered 2 because it has in list. I hape this data help you.
I'd personally consider using a set
instead of a list
as long as the order of your elements isn't necessarily important. Then you can use the discard method:
>>> 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])
How about list comprehension?
a = [x for x in a if x != 10]
A better way to do this would be
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.