set.add() vs set.remove()
set.add() and set.remove() 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.add(): Adds an element to the set if not already present. Its syntax is set.add(x), and it returns none set.remove(): Removes element x; raises KeyError if not found. Its syntax is set.remove(x), and it returns none Example of set.add(): s = {1, 2}
s.add(3) # s = {1, 2, 3}
s.add(1) # s = {1, 2, 3} (unchanged). Example of set.remove(): s = {1, 2, 3}
s.remove(2) # s = {1, 3}
s.remove(4) # KeyError!. Read the full references for set.add() and set.remove() to see parameters, edge cases, and example code side by side. Other Set Methods APIs worth comparing: set.discard(), set.pop(), set.clear(), set.union(), set.intersection(), set.difference().