patternpythonCritical
Is there a simple way to delete a list element by value?
Viewed 0 times
listtheresimplevaluewayelementdelete
Problem
I want to remove a value from a list if it exists in the list (which it may not).
The above gives the error:
So I have to do this:
But is there not a simpler way to do this?
a = [1, 2, 3, 4]
b = a.index(6)
del a[b]
print(a)The above gives the error:
ValueError: list.index(x): x not in list
So I have to do this:
a = [1, 2, 3, 4]
try:
b = a.index(6)
del a[b]
except:
pass
print(a)But is there not a simpler way to do this?
Solution
To remove the first occurrence of an element, use
To remove all occurrences of an element, use a list comprehension:
list.remove:>>> xs = ['a', 'b', 'c', 'd']
>>> xs.remove('b')
>>> print(xs)
['a', 'c', 'd']To remove all occurrences of an element, use a list comprehension:
>>> xs = ['a', 'b', 'c', 'd', 'b', 'b', 'b', 'b']
>>> xs = [x for x in xs if x != 'b']
>>> print(xs)
['a', 'c', 'd']Code Snippets
>>> xs = ['a', 'b', 'c', 'd']
>>> xs.remove('b')
>>> print(xs)
['a', 'c', 'd']>>> xs = ['a', 'b', 'c', 'd', 'b', 'b', 'b', 'b']
>>> xs = [x for x in xs if x != 'b']
>>> print(xs)
['a', 'c', 'd']Context
Stack Overflow Q#2793324, score: 1911
Revisions (0)
No revisions yet.