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

74,220

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])

Solution 3

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

How about list comprehension?

a = [x for x in a if x != 10]

Solution 5

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)
Share:
74,220
JuanPablo
Author by

JuanPablo

Updated on November 06, 2021

Comments

  • JuanPablo
    JuanPablo over 2 years

    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)
    
  • haventchecked
    haventchecked over 10 years
    Using a set when not appropriate can have unintended consequences. From the documentation, Remove the first item from the list whose value is x. It is an error if there is no such item. OP may want to only remove the first item in other use cases, indicating valid duplicates within the list.
  • tscizzle
    tscizzle over 8 years
    It's a good thought, but as @Niklas B. points out, his is "thread-safe", because no matter what, 10 not being there can only ever cause a caught exception. Whereas in this answer, 10 could be removed from a between the if condition being checked and .remove() being called, resulting in an uncaught ValueError. (If you can make a guarantee about a not being modified by anything else, then this is fine, but with the accepted answer you don't even have to think about that possibility.)
  • fuglede
    fuglede over 7 years
    For lambda expressions, it can sometimes be helpful to have a one-liner for the same purpose, and in that case a in 10 and a.remove(10) does the job. It's also not thread-safe though.
  • reteptilian
    reteptilian over 7 years
    Kinda torn on this one ... at what point do you abandon the zen of python for thread safety? Certainly if you are writing a library module that is likely to be used in a multithreaded app you will need to make things more complex and/or document its thread safety (or lack thereof), but should one try to do that in general?
  • raratiru
    raratiru about 6 years
    @reteptilian I think it is not actually the "thread safety" rather than it is "Easier to ask for forgiveness than permission."
  • radiaph
    radiaph about 6 years
    If you care about thread safety you should be using explicit locking.
  • ocket8888
    ocket8888 about 4 years
    The question is specifically about how to ignore the error when attempting to remove something from a list that isn't in that list.
  • Admin
    Admin almost 4 years
    Please explain why think this an improvement over the accepted answer.
  • JJL
    JJL almost 4 years
    @Melvyn, I primarily offered it as an alternative, not necessarily an "improvement". I like that it's one line and readable.
  • ApproachingDarknessFish
    ApproachingDarknessFish about 3 years
    This creates a new list, which is less efficient than modifying an existing one, especially if the item is not found and no copying of elements needs to be done.
  • ApproachingDarknessFish
    ApproachingDarknessFish about 3 years
    Furthermore, it may break references to the existing list, e.g. a = ['foo']; b = a; a = [x for x in a if x != 'bar']; a.append('baz'); print(b) will print ['foo'] whereas using remove will print ['foo', 'baz']. As such I don't consider this a viable generalized alternative to try/remove/except or if/in/remove.