views:

122

answers:

5
a=[1,2,3,4]
b=a.index(6)
del a[b]
print a

it show 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 this is not simple,has any simply way ?

thanks

+3  A: 

To remove an element's first occurrence in a list, simply use list.remove:

>>> a = [1, 2, 3, 4]
>>> a.remove(2)
>>> print a
[1, 3, 4]

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]
jellybean
+1  A: 

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
S.Mark
+2  A: 

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
Roger Pate
+1  A: 

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.

Dave Webb
+1  A: 

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:]
J.F. Sebastian