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
Finding a value in a list and then deleting that index (if it exists) is easier done by just using list's remove method:
>>> a = [1, 2, 3, 4]
>>> try:
... a.remove(6)
... except ValueError:
... pass
...
>>> print a
[1, 2, 3, 4]
>>> try:
... a.remove(3)
... except ValueError:
... pass
...
>>> print a
[1, 2, 4]
If you do this often, you can wrap it up in a function:
def remove_if_exists(L, value):
try:
L.remove(value)
except ValueError:
pass