How can I ignore ValueError when I try to remove an element from a list?
PythonListError HandlingElementsPython Problem Overview
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)
Python Solutions
Solution 1 - Python
A good and thread-safe way to do this is to just try it and ignore the exception:
try:
a.remove(10)
except ValueError:
pass # do nothing!
Solution 2 - Python
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])
Solution 3 - Python
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)
Solution 4 - Python
How about list comprehension?
a = [x for x in a if x != 10]
Solution 5 - Python
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.
Solution 6 - Python
i think the most simple way(may not best way) is write down if statement to check this value is in the list or not, then remove it from list.
if 10 in a:
a.remove(10)
Solution 7 - Python
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']
Solution 8 - Python
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.