This is something that's bothered me for a while, and I can't figure out why anyone would ever want the language to act like this:
In [1]: foo = [1, 2, 3]
In [2]: foo.remove(2) ; foo # okay
Out[2]: [1, 3]
In [3]: foo.remove(4) ; foo # not okay?
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
/home/izkata/<ipython console> in <module>()
ValueError: list.remove(x): x not in list
If the value is already not in the list, then I'd expect a silent success. Goal already achieved. Is there any real reason this was done this way? It forces awkward code that should be much shorter:
for item in items_to_remove:
try:
thingamabob.remove(item)
except ValueError:
pass
Instead of simply:
for item in items_to_remove:
thingamabob.remove(item)
As an aside, no, I can't just use set(thingamabob).difference(items_to_remove) because I do have to retain both order and duplicates.
del foo[foo.index(4)]->ValueError: list.index(x): x not in list. Even if I already had a possible index,del foo[4]->IndexError: list assignment index out of range.delis just as bad as.remove()– Izkata Sep 21 '12 at 16:48[x.remove(i) for i in x[:] if i in y]– faif Sep 21 '12 at 18:22