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

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


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!


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))>>> Sset([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)>>> Sset([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])


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)