Python Sets
A set is an unordered collection of unique, hashable values. O(1) membership tests, plus mathematical set operations.
Create
PYTHON
a = {1, 2, 3}
b = set([1, 1, 2, 3]) # {1, 2, 3} — dedups for you
empty = set() # NOT {} — that's an empty dict
Operations
| Op | Means |
|---|---|
a | b or a.union(b) | Union |
a & b or a.intersection(b) | Intersection |
a - b or a.difference(b) | Difference |
a ^ b or a.symmetric_difference(b) | In one but not both |
a <= b | Subset |
a < b | Proper subset |
Membership is fast
PYTHON
banned = {'spam', 'phish', 'noreply'}
if user.lower() in banned:
reject()
That's O(1). The list equivalent (in [...]) is O(n).
frozenset
Need a set that itself can be a key or set member? Use the immutable frozenset.
PYTHON
cached = {frozenset({'a', 'b'}): 'result'}
Tip: Use sets to dedup a list while preserving uniqueness, but remember the order is not guaranteed. For order-preserving dedup use
list(dict.fromkeys(items)).Example
Example
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # union
print(a & b) # intersection
print(a - b) # difference
print(a ^ b) # symmetric difference
Try it Yourself »
Exercise
Create an empty set (not an empty dict).
s =
()
Three letters; same as the type name.
Discussion
Loading…