[Solved-3 Solutions] Is there a simple way to delete a list element by value?



Error Description:

a=[1,2,3,4]
b=a.index(6)
del a[b]
print a 
click below button to copy the code. By - python tutorial - team
  • The above 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 
click below button to copy the code. By - python tutorial - team

Solution 1:

  • 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'] 
click below button to copy the code. By - python tutorial - team
  • Mind that it does not remove all occurrences of your element. Use a list comprehension for that.
>>> a = [1, 2, 3, 4, 2, 3, 4, 2, 7, 2]
>>> a = [x for x in a if x != 2]
>>> print a
[1, 3, 4, 3, 4, 7] 
click below button to copy the code. By - python tutorial - team

Solution 2:

  • 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) 
click below button to copy the code. By - python tutorial - team
  • or:
try:
    a.remove(c)
except ValueError:
    pass 
click below button to copy the code. By - python tutorial - team

Solution 3:

  • You can do
a=[1,2,3,4]
if 6 in a:
    a.remove(6) 
click below button to copy the code. By - python tutorial - team
  • but above need to search 6 in list a 2 times, so try except would be faster
try:
    a.remove(6)
except:
    pass 
click below button to copy the code. By - python tutorial - team

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