How can I ignore ValueError when I try to remove an element from a list?
Solution 1:
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:
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])