Show the four Python set operations and the operators that express them.
Python sets support four algebraic operations, and each has both an operator and a named method.
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # union - everything in either set
print(a & b) # intersection - shared elements
print(a - b) # difference - in a but not in b
print(a ^ b) # symmetric difference - in one but not both
print(a.union(b)) # same as a | b
print(a.intersection(b)) # same as a & b
print(a.difference(b)) # same as a - b
print(a.symmetric_difference(b)) # same as a ^ b
# In-place versions modify the left operand
a |= {9}
print(a) # {1, 2, 3, 9}The union combines both sets, the intersection keeps only what is in both, the difference keeps what is in the left set but not the right, and the symmetric difference keeps what is in exactly one of them. That last one is the one people misremember — a ^ b is the union of the two differences, not the same as a - b.
The operators exist as shorthand for the methods, and they are the form to use because they read like the maths. The named methods have one extra capability: they accept any iterable, so set.union([1, 2]) works, while {1, 2} | [1, 2] raises a TypeError because a list has no union operation. The in-place operators such as |= and &= modify the left-hand set rather than creating a new one.
One more operation worth knowing is the comparison ones. Sets support <=, <, >, >=, == and !=, and these are subset and superset tests rather than ordering. The strict subset test, a < b, is True only when a is a proper subset of b. This is the idiom for asking whether one group of tags is entirely contained in another.