Sub topic 6
Combining sets: union, intersection, difference
This chapter assumes you can create sets, test membership with in, and know that set elements must be hashable. Here you learn the four operations that build a new set from two or more existing sets. You also learn how the operator forms differ from the method forms, and where each one fails.
The four operations
Python implements the standard set algebra operations as both operators and methods. Each one returns a new set and leaves its inputs unchanged.
| Operation | Operator | Method | Result contains | Column |
|---|---|---|---|---|
| Union | `a \ | b` | `a.union(b)` | Elements in `a`, in `b`, or in both |
| Intersection | `a & b` | `a.intersection(b)` | Elements in both `a` and `b` | |
| Difference | `a - b` | `a.difference(b)` | Elements in `a` that are not in `b` | |
| Symmetric difference | `a ^ b` | `a.symmetric_difference(b)` | Elements in exactly one of `a` or `b` |
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(sorted(a | b)) # [1, 2, 3, 4, 5]
print(sorted(a & b)) # [3, 4]
print(sorted(a - b)) # [1, 2]
print(sorted(b - a)) # [5]
print(sorted(a ^ b)) # [1, 2, 5]
print(sorted(a)) # [1, 2, 3, 4] (unchanged)The examples use sorted() because a set has no guaranteed iteration order. Sorting makes the printed output predictable.
Union
Union collects every element that appears in at least one input. Duplicates collapse automatically, because a set stores each element once.
Two facts help when you check your own results:
a | set()equalsa. The empty set is the identity for union.len(a | b) == len(a) + len(b) - len(a & b). Elements in the overlap are counted twice in the sum, so you subtract them once.
Intersection
Intersection keeps only the elements present in both inputs. Use it to answer "which items do these two collections share?"
admins = {"ana", "bo", "cy"}
active_today = {"bo", "cy", "dee", "eli"}
active_admins = admins & active_today
print(sorted(active_admins)) # ['bo', 'cy']The intersection of any set with the empty set is the empty set. If the intersection is empty, the inputs are disjoint. When you only need that yes-or-no answer, isdisjoint() is a better fit and is covered in the chapter on comparing sets.
Difference
Difference is the one operation where order matters. a - b means "everything in a that is not in b". b - a is a different set.
required = {"python", "git", "sql"}
known = {"python", "excel", "sql"}
print(sorted(required - known)) # ['git'] still to learn
print(sorted(known - required)) # ['excel'] extra skillsDifference is also not associative. Grouping changes the answer:
a = {1, 2, 3}
b = {2, 3, 4}
c = {3, 4, 5}
print(sorted((a - b) - c)) # [1]
print(sorted(a - (b - c))) # [1, 3]Here a - b - c is read left to right, so it means (a - b) - c. Use parentheses when you want the other grouping.
Symmetric difference
Symmetric difference keeps the elements that belong to exactly one of the two sets. It drops everything in the overlap, so it shows what changed between two snapshots.
before = {"a.txt", "b.txt", "c.txt"}
after = {"b.txt", "c.txt", "d.txt"}
changed = before ^ after
print(sorted(changed)) # ['a.txt', 'd.txt']
print(sorted(before - after)) # ['a.txt'] removed
print(sorted(after - before)) # ['d.txt'] addedTwo identities describe it. a ^ b equals (a | b) - (a & b), and it also equals (a - b) | (b - a). Symmetric difference is commutative and associative, so a ^ b ^ c keeps the elements that appear in an odd number of the three sets.
Operators versus methods
The operator and method forms give the same result for two sets. They differ in what they accept.
- Operators require both sides to be sets or frozensets. Any other type raises
TypeError. - Methods accept any iterable, such as a list, a tuple, a string, a
range, or a generator. Python converts it to a set internally. union,intersectionanddifferenceaccept several arguments in one call.symmetric_differenceaccepts exactly one argument.
a = {1, 2, 3}
print(sorted(a.union([3, 4], range(10, 12)))) # [1, 2, 3, 4, 10, 11]
print(sorted(a.intersection([2, 3, 9]))) # [2, 3]
print(sorted(a.difference([1], (2,)))) # [3]
try:
a | [4]
except TypeError as e:
print(e) # unsupported operand type(s) for |: 'set' and 'list'The method forms are convenient when your data is already in a list, because you skip the explicit set(...) conversion. The elements of the iterable must still be hashable. a.union([[1], [2]]) raises TypeError: unhashable type: 'list'.
Combining more than two sets
You can chain operators, or pass several arguments to a method. For a whole collection of sets, call the method on the set class and unpack the collection with *:
groups = [{1, 2, 3}, {2, 3, 4}, {3, 4, 5}]
print(sorted(set.union(*groups))) # [1, 2, 3, 4, 5]
print(sorted(set.intersection(*groups))) # [3]This works because set.union is the unbound method, so the first set in the list plays the role of self. The list must contain at least one set. set.intersection(*[]) raises TypeError, because there is no first set to start from. For the union you can avoid that edge case by starting from an empty set: set().union(*groups) works even when groups is empty.
The multi-argument method form is also more efficient than chaining operators. a | b | c builds an intermediate set for a | b. a.union(b, c) builds the result in one pass.
Precedence
When you mix operators in one expression, Python applies them in this order, from highest to lowest: -, then &, then ^, then |.
a = {1, 2, 3}
b = {2, 3, 4}
c = {3, 4, 5}
print(sorted(a | b & c)) # [1, 2, 3, 4] same as a | (b & c)
print(sorted((a | b) & c)) # [3, 4]Most readers do not remember this ordering, so add parentheses whenever an expression mixes two different operators. The parentheses cost nothing and prevent misreadings.
What type comes back
The result type follows the left operand. A set on the left gives a set, and a frozenset on the left gives a frozenset, even when the right side is the other type.
fs = frozenset({1, 2})
s = {2, 3}
print(fs | s) # frozenset({1, 2, 3})
print(s | fs) # {1, 2, 3}
print(type(fs & s).__name__) # frozenset
print(type(s & fs).__name__) # setRemember this when the result needs to be hashable, for example as a dictionary key. Put the frozenset on the left, or wrap the result with frozenset(...).
A worked example
Suppose you manage access to a service. You have three sets of user names and want a report.
employees = {"ana", "bo", "cy", "dee"}
vpn_users = {"bo", "cy", "eli", "fay"}
badge_users = {"ana", "cy", "dee", "fay"}
everyone_known = employees | vpn_users | badge_users
all_three = employees & vpn_users & badge_users
outsiders = (vpn_users | badge_users) - employees
only_vpn = vpn_users - employees - badge_users
print(sorted(everyone_known)) # ['ana', 'bo', 'cy', 'dee', 'eli', 'fay']
print(sorted(all_three)) # ['cy']
print(sorted(outsiders)) # ['eli', 'fay']
print(sorted(only_vpn)) # ['eli']Each line of the report is one expression. The parentheses in outsiders matter. Without them, - would bind tighter than |, and the expression would mean vpn_users | (badge_users - employees), which gives a different answer.
Edge cases to remember
- Empty sets.
a | set()anda - set()return a copy ofa.a & set()returns an empty set. - Same set on both sides.
a | aanda & aequala.a - aanda ^ aare empty. - No arguments.
a.union()returns a shallow copy ofa. This is a handy way to copy a set. - Cost. Union and symmetric difference take time proportional to the sizes of both inputs. Intersection takes time proportional to the smaller input, because Python iterates over the smaller set and looks each element up in the larger one. Difference takes time proportional to the size of the left operand, because it iterates over
aand checks each element againstb. - Order. The result's iteration order is not defined. Never write code that depends on it.
Exercise
Given x = {1, 2, 3, 4}, y = {3, 4, 5} and z = {4, 5, 6}, what do x - y - z and x - (y - z) evaluate to, and why do they differ?
Show answer
x - y - z is (x - y) - z. First x - y is {1, 2}, and removing z changes nothing, so the result is {1, 2}. For x - (y - z), first y - z is {3}, and x - {3} is {1, 2, 4}. They differ because difference is not associative: the grouping decides which elements are removed from x.
Exercise
You have words = ["red", "blue", "red", "green"] and banned = {"blue", "pink"}. Write one expression using a set method, with no explicit set(...) call, that gives the unique words that are not banned. What does it return?
Show answer
Use banned on the right of a difference. Since banned is already a set and words is a list, call the method on a set built from the words, or go the other way with a method that accepts the list. With no set(...) call, {*words}.difference(banned) works and returns {'red', 'green'}. The method form of difference accepts any iterable, so banned.symmetric_difference would not be the right tool here. Only difference removes the banned words without adding 'pink'.
Exercise
What is the type of {1, 2} & frozenset({2, 3}), and what is the type of frozenset({2, 3}) & {1, 2}?
Show answer
The first is a set ({2}) and the second is a frozenset (frozenset({2})). The result type follows the left operand.