Python Sets: Unique Values, Union and Intersection
A set is an unordered collection of unique values. Adding something that is already present has no effect, which makes sets the quickest way to remove duplicates. Checking whether a value is in a set is also very fast, even with millions of items, because sets use the same hashing as dictionary keys.
Creating sets
Write a set with braces: {"python", "sql"}, or build one from any iterable with set(). In the example, "python" appears twice in the literal but the set holds it once, so len(tags) is 3. set("banana") gives the distinct letters of a word.
There is one trap: {} creates an empty dictionary, not an empty set. Use set() for that.
Set algebra
Sets support the operations you may remember from school, each available as an operator or a method:
a | b(ora.union(b)): everything in either set.a & b(intersection): only what both have.a - b(difference): what is inabut not inb.a ^ b(symmetric_difference): what is in exactly one of them.
Expected output
3 True
{1, 2, 3, 4, 5}
{3, 4}
{1, 2}
{1, 2, 5}
['a', 'b', 'n']
<class 'set'> <class 'dict'>Sets have no order, so you cannot index them and their printed order is not something to rely on. When you need a stable order for display, use sorted(), which returns a list. Small integer sets happen to print in ascending order, but that is a detail of how CPython stores them.
Changing a set
add(x) inserts one value, update(iterable) inserts many, discard(x) removes a value if present, and remove(x) does the same but raises KeyError when it is missing. Like dictionary keys, set members must be hashable, so you can put strings, numbers and tuples in a set, but not lists. If you need an immutable set, for example as a dictionary key, use frozenset.
Common mistakes
- Writing
{}for an empty set. - Expecting a set to keep insertion order or allow
s[0]. - Converting to a set to deduplicate and then being surprised that the original order is lost. When order matters,
list(dict.fromkeys(items))keeps the first occurrence of each value.
Summary
- Sets hold unique, hashable values with no order.
|,&,-and^compute union, intersection, difference and symmetric difference.set()is the empty set;{}is an empty dict.
Quiz: Sets