Set operations¶
This reference documents all methods and operators available on Python set objects.
Adding and removing¶
add()¶
Add an element to the set. Has no effect if the element is already present.
remove()¶
Remove an element from the set. Raises KeyError if the element is not found.
discard()¶
Remove an element from the set if it is present. Does not raise an error if the element is missing.
pop()¶
Remove and return an arbitrary element. Raises KeyError if the set is empty.
clear()¶
Remove all elements from the set.
Set algebra¶
Union¶
Items in either set (or both).
| Form | Syntax |
|---|---|
| Operator | a | b |
| Method | a.union(b) |
| In-place | a |= b or a.update(b) |
Intersection¶
Items in both sets.
| Form | Syntax |
|---|---|
| Operator | a & b |
| Method | a.intersection(b) |
| In-place | a &= b or a.intersection_update(b) |
Difference¶
Items in the first set but not the second.
| Form | Syntax |
|---|---|
| Operator | a - b |
| Method | a.difference(b) |
| In-place | a -= b or a.difference_update(b) |
Symmetric difference¶
Items in either set, but not both.
| Form | Syntax |
|---|---|
| Operator | a ^ b |
| Method | a.symmetric_difference(b) |
| In-place | a ^= b or a.symmetric_difference_update(b) |
Comparison¶
issubset()¶
Return True if every element of the set is in the other set. Equivalent to set <= other.
Use set < other to test for a proper subset (subset but not equal).
issuperset()¶
Return True if every element of the other set is in this set. Equivalent to set >= other.
Use set > other to test for a proper superset.
isdisjoint()¶
Return True if the two sets have no elements in common.
Other operations¶
copy()¶
Return a shallow copy of the set.
frozenset¶
A frozenset is an immutable version of a set. It supports all set operations except those that modify the set.
Frozen sets can be used as dictionary keys or as elements of other sets.
Summary of operators versus methods¶
| Operation | Operator | Method |
|---|---|---|
| Union | | |
union() |
| Intersection | & |
intersection() |
| Difference | - |
difference() |
| Symmetric difference | ^ |
symmetric_difference() |
| Subset | <= |
issubset() |
| Proper subset | < |
— |
| Superset | >= |
issuperset() |
| Proper superset | > |
— |