Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

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 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?

like image 904
zjm1126 Avatar asked May 08 '10 07:05

zjm1126


People also ask

How do I remove a specific element from a list?

There are three ways in which you can Remove elements from List: Using the remove() method. Using the list object's pop() method. Using the del operator.

How do I remove a specific element from a list in Python?

In Python, use list methods clear() , pop() , and remove() to remove items (elements) from a list. It is also possible to delete items using del statement by specifying a position or range with an index or slice.

What are two ways to remove an element from a list?

The methods are remove(), pop() and clear() . Besides the list methods, you can also use a del keyword to remove items from a list.


11 Answers

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] 
like image 139
Johannes Charra Avatar answered Oct 19 '22 12:10

Johannes Charra


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.

like image 21
Dave Webb Avatar answered Oct 19 '22 11:10

Dave Webb


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
like image 42
YOU Avatar answered Oct 19 '22 10:10

YOU


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)
like image 25
mathwizurd Avatar answered Oct 19 '22 11:10

mathwizurd


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:]
like image 32
jfs Avatar answered Oct 19 '22 10:10

jfs


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')
like image 39
Felk Avatar answered Oct 19 '22 12:10

Felk


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]

like image 21
gil Avatar answered Oct 19 '22 10:10

gil


In one line:

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

sometimes it usefull.

Even easier:

if 'b' in a: a.remove('b')
like image 36
Andrey Topoleov Avatar answered Oct 19 '22 10:10

Andrey Topoleov


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.

like image 22
GreenAsJade Avatar answered Oct 19 '22 12:10

GreenAsJade


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]
like image 20
Pagol Avatar answered Oct 19 '22 12:10

Pagol


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]
like image 29
Chase Adams Avatar answered Oct 19 '22 11:10

Chase Adams