1

.discard(x): This operation removes element from the set. If element does not exist, it does not raise a KeyError.

.remove(x): This operation removes element from the set. If element does not exist, it raises a KeyError.

So my question is, where is the reason to use remove(x) function since it can cause problem to our program by erasing an error. I feel like it is useless function since discard(x) does the exact same thing without causing any unpredictable behavior to our program.

Ollie
  • 1,641
  • 1
  • 13
  • 31
OG_
  • 49
  • 6
  • 2
    sometimes you want to know about errors and act accordingly... – hiro protagonist Jun 03 '18 at 10:30
  • 1
    Wouldn't you **want** to get an error if you are trying to remove and element that doesn't exist? I mean... you thought it was there - but it's not - I would think this is an error that you would want to know about. – Lix Jun 03 '18 at 10:30

1 Answers1

4

Sometimes errors are useful. You can use try: except: to catch these errors, and do different things depending on whether that piece of code caused an error. For example:

try:
    list.remove(elem)
    print("Item removed!")
except KeyError as e:
    print("Sorry, that item was not in the set. More information: %s".format(str(e)))
Ollie
  • 1,641
  • 1
  • 13
  • 31