Sub topic 6
Combining sets: union, intersection, difference
This chapter assumes you can create sets, test membership with in, and add or remove elements. Here you will combine two sets into a new one using the four standard set algebra operations.
The four operations
Each operation has an operator form and a method form. All of them return a new set and leave the originals unchanged.
| Operation | Operator | Method | Result contains | Column |
|---|---|---|---|---|
| Union | `a \ | b` | `a.union(b)` | elements in either set |
| Intersection | `a & b` | `a.intersection(b)` | elements in both sets | |
| Difference | `a - b` | `a.difference(b)` | elements in `a` but not in `b` | |
| Symmetric difference | `a ^ b` | `a.symmetric_difference(b)` | elements in exactly one set |
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(sorted(a | b)) # [1, 2, 3, 4, 5] union
print(sorted(a & b)) # [3, 4] intersection
print(sorted(a - b)) # [1, 2] difference
print(sorted(a ^ b)) # [1, 2, 5] symmetric differenceThe examples call sorted() before printing because a set has no guaranteed order. Sorting makes the output the same on every run.
Operators versus methods
The operators require both sides to be sets (or frozensets). The methods accept any iterable, so you can skip building a temporary set.
a = {1, 2, 3}
print(sorted(a.union([3, 4, 5]))) # [1, 2, 3, 4, 5]
print(sorted(a.intersection("1234"))) # [] because the string holds characters, not ints
try:
a | [3, 4, 5]
except TypeError as e:
print(e) # unsupported operand type(s) for |: 'set' and 'list'The second line shows a common mistake: the iterable's elements must be equal to the set's elements. The string "1234" contains the characters '1', '2', and so on, which are not equal to the integers 1, 2.
The methods also accept several arguments at once, which is useful for more than two sets.
a = {1, 2, 3, 4}
b = {2, 3, 4, 5}
c = {3, 4, 5, 6}
print(sorted(a.union(b, c))) # [1, 2, 3, 4, 5, 6]
print(sorted(a.intersection(b, c))) # [3, 4]
print(sorted(a.difference(b, c))) # [1]a.difference(b, c) removes anything found in b or in c from a.
Difference is not symmetric
Union, intersection, and symmetric difference give the same result when you swap the operands. Difference does not.
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(sorted(a - b)) # [1, 2]
print(sorted(b - a)) # [5]Symmetric difference equals (a - b) | (b - a). It answers the question "what changed between these two sets?"
Chaining and precedence
Operators can be chained, but they have different precedence. & binds tighter than ^, which binds tighter than |. The - operator has the same precedence as arithmetic subtraction and binds tighter than all three of them. Use parentheses when you mix operators.
a = {1, 2}
b = {2, 3}
c = {3, 4}
print(sorted(a | b & c)) # [1, 2, 3] b & c runs first
print(sorted((a | b) & c)) # [3] parentheses change the resultA worked example
Suppose two teams list the tools they use. You want to see what they share and where they differ.
team_a = {"git", "docker", "python", "vim"}
team_b = {"git", "python", "vscode", "terraform"}
print("shared:", sorted(team_a & team_b))
print("only A:", sorted(team_a - team_b))
print("only B:", sorted(team_b - team_a))
print("everything:", sorted(team_a | team_b))
print("not shared:", sorted(team_a ^ team_b))Output:
# shared: ['git', 'python']
# only A: ['docker', 'vim']
# only B: ['terraform', 'vscode']
# everything: ['docker', 'git', 'python', 'terraform', 'vim', 'vscode']
# not shared: ['docker', 'terraform', 'vim', 'vscode']Common errors
- Writing
{}for an empty starting set. It creates a dict, so{} | {1}raises aTypeError. Useset(). - Using
+to combine sets. Sets do not support it. Use|. - Expecting
a - bto equalb - a. - Passing a list to an operator such as
|. Use the method form, or wrap the list inset(). - Relying on the printed order of the result. Sort it if the order matters.
Exercise
Given x = {1, 2, 3, 4} and y = {3, 4, 5, 6}, what do sorted(x - y) and sorted(x ^ y) print? Then write one expression that gives the elements of x found in none of y and {1}.
Show answer
sorted(x - y) prints [1, 2], and sorted(x ^ y) prints [1, 2, 5, 6]. The expression x - y - {1} (or x.difference(y, {1})) gives {2}.
Exercise
Why does {1, 2}.union("12") return {1, 2, '1', '2'} rather than {1, 2}?
Show answer
The method accepts any iterable, and iterating over a string yields single-character strings. The strings '1' and '2' are not equal to the integers 1 and 2, so they are added as new elements.