Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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) 
like image 504
JuanPablo Avatar asked Mar 28 '12 20:03

JuanPablo


People also ask

How do you stop ValueError in Python?

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.

How do you exclude an element from a list?

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.

How do I remove a specific string from a list?

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 do you exclude an element from a list in Python?

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.


2 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! 
like image 126
Niklas B. Avatar answered Oct 05 '22 21:10

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]) 
like image 44
g.d.d.c Avatar answered Oct 05 '22 21:10

g.d.d.c