A set is an unordered collection of unique, hashable values, offering fast O(1) average membership testing and the classic mathematical set operations.
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # union: {1,2,3,4,5,6}
print(a & b) # intersection: {3,4}
print(a - b) # difference: {1,2}
print(a ^ b) # symmetric difference: {1,2,5,6}
a.add(10) # add a single element
a.discard(1) # remove if present, no error if missing (.remove() raises if missing)
unique = set([1, 2, 2, 3, 3, 3]) # {1, 2, 3} — a fast way to deduplicate a list
print(7 in a) # O(1) average membership test
Sets automatically eliminate duplicates, which makes set(some_list) one of the most common, idiomatic ways to deduplicate a collection in Python — far faster than checking if item not in result_list inside a loop, since list membership testing is O(n) while set membership testing is O(1) on average.
The four set operators — | (union), & (intersection), - (difference), ^ (symmetric difference) — directly mirror set notation from mathematics, and each has an equivalent method (.union(), .intersection(), etc.) that additionally accepts any iterable, not just another set.
frozenset is an immutable version of set — usable as a dict key or as an element of another set, exactly the way tuples serve as the immutable counterpart to lists.