# Is there a quick way to remove a list element based on its value?

## Problem

If a value already exists in a list, I want to remove it (which it may not).

``````a = [1, 2, 3, 4]
b = a.index(6)

del a[b]
print(a)
``````

The following error is shown in the above scenario (when it does not exist):

``````Traceback (most recent call last):
File "D:\zjm_code\a.py", line 6, in <module>
b = a.index(6)
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)
``````

Isn’t there a more straightforward approach?

## Solution #1

Simply use list to eliminate an element’s initial appearance in a list. remove:

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

Keep in mind that it does not eliminate all instances of your element. To do so, use a list comprehension exercise.

``````>>> 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]
``````

## Solution #2

If you ask Python to do something it can’t, it will usually throw an Exception, therefore you’ll have to perform one of two things:

``````if c in a:
a.remove(c)
``````

or:

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

An exception isn’t always a terrible thing, as long as you anticipate it and handle it properly.

## Solution #3

You can do

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

However, because searching 6 items in the list twice is inconvenient, trying unless would be a better option.

``````try:
a.remove(6)
except:
pass
``````

## Solution #4

Consider:

``````a = [1,2,2,3,4,5]
``````

You may use Python’s filter function to remove all occurrences. For instance, consider the following:

``````a = list(filter(lambda x: x!= 2, a))
``````

As a result, all elements of a!= 2 would be preserved.

To simply remove one of the elements, use

``````a.remove(2)
``````

## Solution #5

Here’s how to accomplish it in real time (without using a list):

``````def remove_all(seq, value):
pos = 0
for item in seq:
if item != value:
seq[pos] = item
pos += 1
del seq[pos:]
``````