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)
Author by
JuanPablo
Updated on November 06, 2021Comments
-
JuanPablo over 2 years
How can I ignore the "not in list" error message if I call
a.remove(x)
whenx
is not present in lista
?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 over 10 yearsUsing 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 over 8 yearsIt'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 froma
between theif
condition being checked and.remove()
being called, resulting in an uncaughtValueError
. (If you can make a guarantee abouta
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 over 7 yearsFor 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 over 7 yearsKinda 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 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 about 6 yearsIf you care about thread safety you should be using explicit locking.
-
ocket8888 about 4 yearsThe question is specifically about how to ignore the error when attempting to remove something from a list that isn't in that list.
-
Admin almost 4 yearsPlease explain why think this an improvement over the accepted answer.
-
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 about 3 yearsThis 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 about 3 yearsFurthermore, 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 usingremove
will print['foo', 'baz']
. As such I don't consider this a viable generalized alternative totry/remove/except
orif/in/remove
.