Set Methods
Set methods are pure. Methods with mutating Python names return a new set instead of changing the receiver.
Signatures
Section titled “Signatures”| Method | Returns | Notes |
| ------------------------------- | ------------------------- | ------------------------------------------------------ |
| s.add(elem) | set | Adds a hashable element. |
| s.remove(elem) | set \| err | Removes elem, or returns KeyError/NLK4003. |
| s.discard(elem) | set | Removes elem when present. |
| s.pop() | tuple[item, set] \| err | Removes the first stored item, or errors when empty. |
| s.clear() | set | Returns an empty set. |
| s.copy() | set | Returns a shallow copy. |
| s.union(other) | set | Union with a set, list, tuple, dict, or string. |
| s.intersection(other) | set | Intersection with a set, list, tuple, dict, or string. |
| s.difference(other) | set | Difference from a set, list, tuple, dict, or string. |
| s.symmetric_difference(other) | set | Symmetric difference with another iterable. |
| s.issubset(other) | bool | Whether s is a subset of other. |
| s.issuperset(other) | bool | Whether s is a superset of other. |
| s.isdisjoint(other) | bool | Whether s shares no items with other. |
When a dict is accepted as other, its keys are used.
The set operation methods accept any of these iterable values: set, list, tuple, dict, or string. Dict inputs use keys. Duplicate values collapse to one stored element.
Sets have stable insertion order. add preserves the position of an element already present and
appends a new element. Removing and then adding an element places it at the end. pop() removes the
first stored element. intersection and difference retain surviving left-hand elements in
left-hand order. union retains the left-hand order and appends new right-hand elements in their
iteration order. symmetric_difference retains left-only elements first, then appends right-only
elements in right-hand order. Set equality ignores order.
When both operands are sets, the operators are equivalent to the corresponding methods:
- the pipe operator is equivalent to
union &is equivalent tointersection-is equivalent todifference^is equivalent tosymmetric_difference
Unlike the methods, these operators require both operands to be sets. For example, {1}.union([2])
succeeds, while {1} | [2] fails with NLK4001.
Errors
Section titled “Errors”Set elements and lookup values must be hashable. remove() returns KeyError/NLK4003 when the
element is absent. pop() returns KeyError/NLK4003 on an empty set. discard() is a no-op when
the element is absent.
Examples
Section titled “Examples”left = {1, 2, 3}right = {3, 4}
print(left.union(right))print(left.intersection(right))print(left.difference(right))print(2 in left)