A set is an unordered collection of unique, hashable items with O(1) membership tests — and real set algebra.
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(a | b) # {1, 2, 3, 4, 5}
print(a & b) # {3, 4}
print(a - b) # {1, 2}
print(a ^ b) # {1, 2, 5}
print({1, 2} <= a) # True| Operator | Method | Meaning |
|---|---|---|
a | b | a.union(b) | In either |
a & b | a.intersection(b) | In both |
a - b | a.difference(b) | In a but not b |
a ^ b | a.symmetric_difference(b) | In exactly one |
a <= b | a.issubset(b) | Every item of a is in b |
Adding & removing
s = set() # {} would be an empty *dict*
s.add(3); s.add(3); s.add(1)
s.discard(99) # no error if missing
print(sorted(s), len(s)) # [1, 3] 2When to reach for a set
xs = [3, 1, 3, 2, 1]
print(list(dict.fromkeys(xs))) # [3, 1, 2]
def has_duplicate(nums):
return len(set(nums)) != len(nums)
print(has_duplicate(xs), has_duplicate([1, 2])) # True False