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

JuanPablo picture JuanPablo · Mar 28, 2012 · Viewed 53.6k times · Source

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)

Answer

Niklas B. picture Niklas B. · Mar 28, 2012

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!