8.2.6. Set Operations#
Sets support mathematical operations that make it easy to compare two collections. Each operation has both an operator shorthand and a method form which produce the same result:
Operation |
Operator |
Method |
Description |
|---|---|---|---|
Union |
|
|
All elements from both sets |
Intersection |
|
|
Only elements common to both sets |
Difference |
|
|
Elements in |
Symmetric Difference |
|
|
Elements in either set, but not in both |
import sys
from pathlib import Path
# Find project root by looking for _config.yml
current = Path.cwd()
for parent in [current, *current.parents]:
if (parent / '_config.yml').exists():
project_root = parent
break
else:
project_root = Path.cwd().parent.parent
# Add project root to path
sys.path.insert(0, str(project_root))
# Import shared teaching helpers and cell magics
from shared import thinkpython, diagram, jupyturtle, structshape
from shared.download import download
a = {1, 2, 3}
b = {3, 4, 5}
Note that, operator forms (|, &, -, ^) require set operands. Method forms are more flexible and can take any iterable.
print(a.union([3, 4, 5])) # works: method accepts iterable
try:
a | [3, 4, 5] # TypeError: right side is a list
except TypeError as e:
print(e)
{1, 2, 3, 4, 5}
unsupported operand type(s) for |: 'set' and 'list'
8.2.6.1. Union#
All elements from both sets
a | b # {1, 2, 3, 4, 5}
a.union(b) # same
{1, 2, 3, 4, 5}
8.2.6.2. Intersection#
Only elements in both sets.
a & b # {3}
a.intersection(b) # same
{3}
8.2.6.3. Difference#
Elements in a but not in b
a - b # {1, 2}
a.difference(b) # same
{1, 2}
8.2.6.4. Symmetric Difference#
Elements in either set, but not both
a ^ b # {1, 2, 4, 5}
a.symmetric_difference(b) # same
{1, 2, 4, 5}
### Exercise: Basic Set Operations
# 1. Create A = {1, 2, 3, 4} and B = {3, 4, 5, 6}.
# 2. Print A | B, A & B, A - B, and A ^ B.
### Your code starts here.
### Your code ends here.
Union: {1, 2, 3, 4, 5, 6}
Intersection: {3, 4}
Difference A-B: {1, 2}
Symmetric Difference: {1, 2, 5, 6}