set.remove() vs set.discard()
set.remove() and set.discard() are both Python Set Methods APIs, and choosing between them is a common point of confusion. This page compares their syntax, parameters, return values, and typical use cases so you can pick the right one. set.remove(): Removes element x; raises KeyError if not found. Its syntax is set.remove(x), and it returns none set.discard(): Removes element x if present (does nothing if not found). Its syntax is set.discard(x), and it returns none Example of set.remove(): s = {1, 2, 3}
s.remove(2) # s = {1, 3}
s.remove(4) # KeyError!. Example of set.discard(): s = {1, 2, 3}
s.discard(2) # s = {1, 3}
s.discard(4) # s = {1, 3} (no error). Read the full references for set.remove() and set.discard() to see parameters, edge cases, and example code side by side. Other Set Methods APIs worth comparing: set.add(), set.pop(), set.clear(), set.union(), set.intersection(), set.difference().