Show the four Python set operations and the operators that express them.
Python sets support four operations that combine two groups of items, and each one has both an operator and a named method.
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b)
print(a & b)
print(a - b)
print(a ^ b)
print(a.union(b))
print(a.intersection(b))
print(a.difference(b))
print(a.symmetric_difference(b))
# The in-place version changes the set on the left.
a |= {9}
print(a)
The union gives you everything that is in either set. The intersection keeps only the items that are in both sets. The difference keeps the items that are in the left set but not in the right one. The symmetric difference keeps the items that are in exactly one of the two sets. The last of those is the one people misremember, because a ^ b is the union of the two differences and not the same thing as a - b.
The operators exist as a short form of the methods, and they are the form to use because they read like the maths that they represent. The named methods have one extra ability, because 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 of its own. The in-place operators, such as |= and &=, change the set on the left instead of building a new one.
One more family of operations is worth knowing, and those are the comparison ones. Sets support <=, <, >, >=, ==, and !=, and these are subset and superset tests rather than ordering tests. The strict subset test a < b is True only when a is a proper subset of b. That is the natural way to ask whether one group of tags sits entirely inside another one.