Set Operations
A set holds unique values in no particular order. It uses the same hashing that makes dict lookups fast. That’s why a set is usually the first thing to try when you need to check whether something is there or remove duplicates. x in some_set takes O(1) time on average, just like a dict lookup. Checking a list takes O(n).
The four operations: | & - ^
O(n + m)Sets have four main operations: union, intersection, difference, and symmetric difference. You can write each one as an operator or as a method. Both do the same thing:
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(sorted(a | b))
print(sorted(a & b))
print(sorted(a - b))
print(sorted(a ^ b))a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(sorted(a.union(b)))
print(sorted(a.intersection(b)))
print(sorted(a.difference(b)))
print(sorted(a.symmetric_difference(b)))The methods have one advantage over the operators. They accept a list or anything else you can loop over, not just another set. You don’t have to turn the other side into a set first:
a = {1, 2, 3, 4}
print(sorted(a.union([5, 6, 7])))The operators are stricter in regular Python. Both sides have to be sets already, or you get a TypeError. Try it below. Remember that the code runner on this page doesn’t check this the same way regular Python does. It might not raise the same error here:
a = {1, 2, 3, 4}
try:
print(a | [5, 6, 7])
except TypeError as e:
print(f"TypeError: {e}")Note
In CPython, a | [5, 6, 7] raises a TypeError because | only accepts another set on the right side. Use the method instead, like a.union(...), if the other side might be a list. That way your code works the same everywhere.
Note
Every result above is wrapped in sorted(). A set doesn’t keep its elements in any fixed order. If you print one directly, the elements can come out in any order. Remember to sort before you print when the order matters.
Removing duplicates from a list
watch outset(my_list) is the fastest way to remove duplicates. It doesn’t keep any order, though. Sort the result before you print it if you need a predictable order:
items = [3, 1, 2, 3, 1, 4]
deduped = set(items)
print(sorted(deduped))Sometimes you need to keep the values in the order they first showed up. dict.fromkeys() removes duplicates the same way a set does. The difference is that a dict remembers the order you added things in:
items = [3, 1, 2, 3, 1, 4]
print(list(dict.fromkeys(items)))Note
Watch out: Don’t expect print(some_set) to print in any particular order. It prints in whatever order the elements are stored in. Small integers can look sorted. Almost anything else will look scrambled. Use dict.fromkeys() instead of a plain set if a problem needs you to remove duplicates and keep the original order.
Common elements between two lists
O(n + m)Turn both lists into sets and take the intersection. This finds the shared elements in linear time. You don’t have to compare every element of one list against every element of the other:
list_a = [1, 2, 3, 4, 5]
list_b = [3, 4, 5, 6, 7]
common = set(list_a) & set(list_b)
print(sorted(common))unhashable type: 'list'
TypeErrorA set stores elements by their hash. A hash only works if the value never changes. Lists can change. That’s why Python won’t let you put one in a set:
try:
bad = {[1, 2], [3, 4]}
except TypeError as e:
print(f"TypeError: {e}")A frozenset is a set that can’t be changed. Because it can’t change, Python can hash it. That means it can go inside another set or be used as a dict key. A regular set can’t do either of those:
fixed = {frozenset([1, 2]), frozenset([3, 4])}
print(len(fixed))
cache = {}
cache[frozenset([1, 2])] = "pair one"
print(cache[frozenset([1, 2])])Note
Only hashable values can go in a set or be used as a dict key. That includes numbers, strings, frozensets, and tuples of hashable values. Lists, dicts, and plain sets can all change. None of them are hashable. Turn each group into a tuple or frozenset first if you need a set of groups or a dict keyed by a group.
issubset, issuperset, and set comprehensions
issubset(), issuperset(), and the <=/>= operators all check whether every element of one set is also in another:
small = {1, 2}
big = {1, 2, 3, 4}
print(small.issubset(big))
print(big.issuperset(small))
print(small <= big)
print(big >= small)You can write set comprehensions the same way you write list and dict comprehensions. Just use {...} instead of [...]:
evens = {n for n in range(10) if n % 2 == 0}
print(sorted(evens))Where set operations show up in interviews
You’ll use a seen set more than anything else. It keeps track of which nodes or cells you’ve already visited. That way you never process the same one twice.
- Graph Breadth First Search uses a visited set in almost every problem. It keeps the same node from being added to the queue more than once.
- Graph DFS problems use the same idea. You add each node to the visited set as the search reaches it.
- Sets help outside of graphs too. Problems that ask you to "find duplicates" or "find elements that appear in both" are almost always faster with a set than with nested loops.