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

Question:

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)
Asked By: JuanPablo

||

Answers:

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!
Answered By: Niklas B.

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])
Answered By: g.d.d.c

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)
Answered By: reteptilian

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.

Answered By: Amey Kasar

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.

Answered By: saumya pani

How about list comprehension?

a = [x for x in a if x != 10]
Answered By: JJL

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']
Answered By: Phil S

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)
Answered By: ehsan bakefayat