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?
To remove an element's first occurrence in a list, simply use
>>> 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]
Read more... Read less...
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)
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.
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
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
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:]
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)
[0, 0, 2, 3, 4]