Sub topic 5
Combining sets: union, intersection, difference
This chapter assumes you can write Python loops and functions, know what a set is (an unordered collection of unique, hashable values), and have a basic sense of Big-O notation. Earlier chapters showed how a set removes duplicates and answers membership tests quickly. Here you will combine whole sets with a single expression.
The three core operations
Three questions come up constantly when you compare two collections:
- Which items appear in either one? That is the union.
- Which items appear in both? That is the intersection.
- Which items appear in the first but not the second? That is the difference.
Python has an operator for each one.
a = {1, 2, 3}
b = {3, 4}
print(a | b) # union: {1, 2, 3, 4}
print(a & b) # intersection: {3}
print(a - b) # difference: {1, 2}Each expression returns a new set. The original sets are unchanged. Printed order may vary, because sets do not promise an order.
Method forms
Each operator also has a method. The methods accept any iterable, not only sets, so you can skip building a temporary set.
a = {1, 2, 3}
print(a.union([3, 4, 5])) # {1, 2, 3, 4, 5}
print(a.intersection([2, 3, 9])) # {2, 3}
print(a.difference([1])) # {2, 3}The operators require both sides to be sets. Writing a | [4] raises a TypeError, while a.union([4]) works.
A worked example
Suppose you have the user IDs that logged in on Monday and on Tuesday. You want three answers.
monday = {"ana", "ben", "cy", "dee"}
tuesday = {"ben", "dee", "eli"}
returning = monday & tuesday
new_on_tuesday = tuesday - monday
seen_any_day = monday | tuesday
print(sorted(returning)) # ['ben', 'dee']
print(sorted(new_on_tuesday)) # ['eli']
print(sorted(seen_any_day)) # ['ana', 'ben', 'cy', 'dee', 'eli']The code uses sorted to print in a stable order. This follows the rule from the iteration-order discussion: do not rely on the order of a set.
Related operations
Two more operators are worth knowing.
| Operator | Meaning | Example result for `{1, 2, 3}` and `{3, 4}` |
|---|---|---|
| `a ^ b` | Symmetric difference: in exactly one set | `{1, 2, 4}` |
| `a <= b` | Subset test: every item of `a` is in `b` | `False` |
Difference is not symmetric. a - b and b - a give different results, which is a common source of bugs when you swap the operands.
Why it is fast
Intersection loops over the smaller set and checks each item in the larger one. Each check is an average constant-time hash lookup. The cost is therefore proportional to the size of the smaller set, not the product of both sizes. The list-based version, with a membership test against a list inside a loop, takes time proportional to the product of the two lengths.
# Slow for large inputs: each "in" scans a list
common = [x for x in list_a if x in list_b]
# Fast: hashing does the lookups
common = set(list_a) & set(list_b)Building the sets costs one pass over each list. The set version loses the original order and drops duplicates, so use the list version if you need either.
Common errors
- Writing
{}for an empty set. That creates an empty dict. Useset(). - Putting unhashable items, such as lists, into a set. Convert them to tuples first.
- Expecting
a | bto modifya. Usea |= bora.update(b)for in-place changes.
Exercise
Given x = {1, 2, 3, 4} and y = {3, 4, 5}, what do x - y, y - x and x ^ y return?
Show answer
x - y is {1, 2}, y - x is {5}, and x ^ y is {1, 2, 5}. The symmetric difference is the union of the two one-sided differences.
Exercise
You have two lists of order IDs, shipped and paid. Write one expression that gives the IDs that were shipped but not paid.
Show answer
set(shipped) - set(paid). You can also write set(shipped).difference(paid), which avoids building the second set yourself.