Set Methods
Set methods reference. Most set operations have both a method form and an operator form — they're equivalent.
Add & remove
| Method | What it does |
|---|---|
add(x) | Add an element. |
update(iter) | Add many at once. |
remove(x) | Remove x; KeyError if missing. |
discard(x) | Remove x; do nothing if missing. |
pop() | Remove and return arbitrary element. |
clear() | Empty. |
Set algebra
| Method | Operator | Returns |
|---|---|---|
union(other) | a \| b | All elements in either. |
intersection(other) | a & b | In both. |
difference(other) | a - b | In a, not in b. |
symmetric_difference(other) | a ^ b | In one, not both. |
issubset(other) | a <= b | True if a is a subset. |
issuperset(other) | a >= b | True if a contains b. |
isdisjoint(other) | — | True if no common elements. |
In-place
Each set-algebra method has an *_update in-place version: intersection_update, difference_update, symmetric_difference_update. Operators have &= -= ^= |=.
Membership is O(1)
PYTHON
banned = {'spam', 'phish', 'noreply'}
if user in banned:
reject()
frozenset
An immutable set — hashable, so it can be used as a dict key or a member of another set. Build with frozenset(iter).
Tip: Sets dedup but don't preserve order. For order-preserving dedup use
list(dict.fromkeys(items)).Example
Example
a = {1, 2, 3}
b = {2, 3, 4}
print(a.union(b))
print(a.intersection(b))
print(a.difference(b))
print(a.issubset({1, 2, 3, 4}))
Try it Yourself »
Exercise
Remove an element without raising if absent.
s.
(x)
Seven letters.
Discussion
Loading…