I want to remove a value from a list if it exists in the list (which it may not).
a = [1, 2, 3, 4]
b = a.index(6)
del a[b]
print(a)
The abov
this is my answer, just use while and for
def remove_all(data, value):
i = j = 0
while j < len(data):
if data[j] == value:
j += 1
continue
data[i] = data[j]
i += 1
j += 1
for x in range(j - i):
data.pop()
Another possibility is to use a set instead of a list, if a set is applicable in your application.
IE if your data is not ordered, and does not have duplicates, then
my_set=set([3,4,2])
my_set.discard(1)
is error-free.
Often a list is just a handy container for items that are actually unordered. There are questions asking how to remove all occurences of an element from a list. If you don't want dupes in the first place, once again a set is handy.
my_set.add(3)
doesn't change my_set from above.
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.
As stated by numerous other answers, list.remove()
will work, but throw a ValueError
if the item wasn't in the list. With python 3.4+, there's an interesting approach to handling this, using the suppress contextmanager:
from contextlib import suppress
with suppress(ValueError):
a.remove('b')
In one line:
a.remove('b') if 'b' in a else None
sometimes it usefull.
Even easier:
if 'b' in a: a.remove('b')