Is there a simple way to delete a list element by value? Is there a simple way to delete a list element by value? python python

Is there a simple way to delete a list element by value?


To remove an element's first occurrence in a list, simply use list.remove:

>>> a = ['a', 'b', 'c', 'd']>>> a.remove('b')>>> print(a)['a', 'c', 'd']

Mind that it does not remove all occurrences of your element. Use a list comprehension for that.

>>> a = [10, 20, 30, 40, 20, 30, 40, 20, 70, 20]>>> a = [x for x in a if x != 20]>>> print(a)[10, 30, 40, 30, 40, 70]


Usually Python will throw an Exception if you tell it to do something it can't so you'll have to do either:

if c in a:    a.remove(c)

or:

try:    a.remove(c)except ValueError:    pass

An Exception isn't necessarily a bad thing as long as it's one you're expecting and handle properly.


You can do

a=[1,2,3,4]if 6 in a:    a.remove(6)

but above need to search 6 in list a 2 times, so try except would be faster

try:    a.remove(6)except:    pass


matomo