Removing an element not currently in a list: ValueError?

Posted by Izkata on Programmers See other posts from Programmers or by Izkata
Published on 2012-09-21T14:24:51Z Indexed on 2012/09/21 15:52 UTC
Read the original article Hit count: 217

Filed under:
|

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.

© Programmers or respective owner

Related posts about design

Related posts about python