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

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 above case (in which it does not exist) shows the following error:

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)

But is there not a simpler way to do this?

This question is related to python list

The answer is


In one line:

a.remove('b') if 'b' in a else None

sometimes it usefull.

Even easier:

if 'b' in a: a.remove('b')

With a for loop and a condition:

def cleaner(seq, value):    
    temp = []                      
    for number in seq:
        if number != value:
            temp.append(number)
    return temp

And if you want to remove some, but not all:

def cleaner(seq, value, occ):
    temp = []
    for number in seq:
        if number == value and occ:
            occ -= 1
            continue
        else:
            temp.append(number)
    return temp

Say for example, we want to remove all 1's from x. This is how I would go about it:

x = [1, 2, 3, 1, 2, 3]

Now, this is a practical use of my method:

def Function(List, Unwanted):
    [List.remove(Unwanted) for Item in range(List.count(Unwanted))]
    return List
x = Function(x, 1)
print(x)

And this is my method in a single line:

[x.remove(1) for Item in range(x.count(1))]
print(x)

Both yield this as an output:

[2, 3, 2, 3, 2, 3]

Hope this helps. PS, pleas note that this was written in version 3.6.2, so you might need to adjust it for older versions.


If your elements are distinct, then a simple set difference will do.

c = [1,2,3,4,'x',8,6,7,'x',9,'x']
z = list(set(c) - set(['x']))
print z
[1, 2, 3, 4, 6, 7, 8, 9]

Consider:

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

To take out all occurrences, you could use the filter function in python. For example, it would look like:

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

So, it would keep all elements of a != 2.

To just take out one of the items use

a.remove(2)

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')

arr = [1, 1, 3, 4, 5, 2, 4, 3]

# to remove first occurence of that element, suppose 3 in this example
arr.remove(3)

# to remove all occurences of that element, again suppose 3
# use something called list comprehension
new_arr = [element for element in arr if element!=3]

# if you want to delete a position use "pop" function, suppose 
# position 4 
# the pop function also returns a value
removed_element = arr.pop(4)

# u can also use "del" to delete a position
del arr[4]

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.


 list1=[1,2,3,3,4,5,6,1,3,4,5]
 n=int(input('enter  number'))
 while n in list1:
    list1.remove(n)
 print(list1)

Maybe your solutions works with ints, but It Doesnt work for me with dictionarys.

In one hand, remove() has not worked for me. But maybe it works with basic Types. I guess the code bellow is also the way to remove items from objects list.

In the other hand, 'del' has not worked properly either. In my case, using python 3.6: when I try to delete an element from a list in a 'for' bucle with 'del' command, python changes the index in the process and bucle stops prematurely before time. It only works if You delete element by element in reversed order. In this way you dont change the pending elements array index when you are going through it

Then, Im used:

c = len(list)-1
for element in (reversed(list)):
    if condition(element):
        del list[c]
    c -= 1
print(list)

where 'list' is like [{'key1':value1'},{'key2':value2}, {'key3':value3}, ...]

Also You can do more pythonic using enumerate:

for i, element in enumerate(reversed(list)):
    if condition(element):
        del list[(i+1)*-1]
print(list)

We can also use .pop:

>>> lst = [23,34,54,45]
>>> remove_element = 23
>>> if remove_element in lst:
...     lst.pop(lst.index(remove_element))
... 
23
>>> lst
[34, 54, 45]
>>> 

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()

If you know what value to delete, here's a simple way (as simple as I can think of, anyway):

a = [0, 1, 1, 0, 1, 2, 1, 3, 1, 4]
while a.count(1) > 0:
    a.remove(1)

You'll get [0, 0, 2, 3, 4]


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.


Here's how to do it inplace (without list comprehension):

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

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

This example is fast and will delete all instances of a value from the list:

a = [1,2,3,1,2,3,4]
while True:
    try:
        a.remove(3)
    except:
        break
print a
>>> [1, 2, 1, 2, 4]

Overwrite the list by indexing everything except the elements you wish to remove

>>> s = [5,4,3,2,1]
>>> s[0:2] + s[3:]
[5, 4, 2, 1]

More generally,

>>> s = [5,4,3,2,1]
>>> i = s.index(3)
>>> s[:i] + s[i+1:]
[5, 4, 2, 1]

This removes all instances of "-v" from the array sys.argv, and does not complain if no instances were found:

while "-v" in sys.argv:
    sys.argv.remove('-v')

You can see the code in action, in a file called speechToText.py:

$ python speechToText.py -v
['speechToText.py']

$ python speechToText.py -x
['speechToText.py', '-x']

$ python speechToText.py -v -v
['speechToText.py']

$ python speechToText.py -v -v -x
['speechToText.py', '-x']

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