Python Set Methods
Every set method — add, remove vs discard (error
semantics matter!), union, intersection, difference,
symmetric_difference, and the set operators.
Add & Remove
set.add
Adds a single hashable element to the set in place. If the element is already present, the set is unchanged (no error).
set.remove
Removes the specified element from the set. Raises KeyError if the element is not present.
set.discard
Removes an element from the set if it is present, and does nothing otherwise. Unlike remove(), never raises an error.
set.pop
Removes and returns an arbitrary element from the set. Raises KeyError if the set is empty.
set.clear
Removes all elements from the set, leaving it empty. Mutates the set in place; other references to the same set see it emptied.
set.update
Adds every element from each iterable argument to s in place. Equivalent to a union but mutates s instead of returning a new set.
Union
Intersection
set.intersection
Returns a NEW set containing only elements found in s AND in every argument. Method form accepts any iterables; & requires sets.
set.intersection_update
Updates s in place, keeping only elements found in s AND every given iterable. The method form accepts iterables; &= requires sets.
Difference
set.difference
Returns a NEW set with elements from s that are NOT in any of the arguments. Method form takes iterables; - requires sets.
set.symmetric_difference
Returns a NEW set with elements in EITHER s or other but not both. Method form takes exactly one iterable; ^ requires a set.
set.difference_update
Removes from s in place every element found in any of the given iterables. Method form accepts iterables; -= requires sets.
Inspection & Subset
set.issubset
Returns True if every element of s is also in other. Method form accepts any iterable; <= requires a set. Use < for strict (proper) subset.
set.issuperset
Returns True if every element of other is in s. Method form accepts any iterable; >= requires a set. Use > for strict (proper) superset.
set.isdisjoint
Returns True if s and other share no elements. Accepts any iterable; there is no operator form.