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)
The best way to dodge the ValueError is by coordinating the number of factors and the number of rundown components. You may likewise utilize a circle to emphasize the components and print them individually.
There are three ways in which you can Remove elements from List: Using the remove() method. Using the list object's pop() method. Using the del operator.
Method #1 : Using remove() This particular method is quite naive and not recommended to use, but is indeed a method to perform this task. remove() generally removes the first occurrence of K string and we keep iterating this process until no K string is found in list.
How to Remove an Element from a List Using the remove() Method in Python. To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method. remove() will search the list to find it and remove it.
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)) >>> 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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With