Python sets work like sets in mathematics: you can join them, intersect them or subtract them. It is the shortest and most readable way to solve problems like "what do these two lists have in common".
In the examples we will use these two sets:
a = {1, 2, 3, 4}
b = {3, 4, 5}
Union: everything that is in either
print(a | b) # {1, 2, 3, 4, 5}
print(a.union(b)) # same
Intersection: what is in both
print(a & b) # {3, 4}
print(a.intersection(b)) # same
Difference: what is in one and not in the other
print(a - b) # {1, 2}
print(b - a) # {5}
print(a.difference(b)) # same as a - b
Unlike union and intersection, the difference is not symmetric: a - b and b - a give different results.
Symmetric difference: what they do not share
print(a ^ b) # {1, 2, 5} (in one or the other, but not in both)
Summary of operations
| Operation | Operator | Method | Result with a and b |
|---|---|---|---|
| Union | a | b | a.union(b) | {1, 2, 3, 4, 5} |
| Intersection | a & b | a.intersection(b) | {3, 4} |
| Difference | a - b | a.difference(b) | {1, 2} |
| Symmetric difference | a ^ b | a.symmetric_difference(b) | {1, 2, 5} |
Comparing sets
print({1, 2} <= {1, 2, 3}) # True: it is a subset
print({1, 2}.issubset({1, 2, 3})) # True
print({1, 2, 3}.issuperset({1})) # True
print({1, 2}.isdisjoint({3, 4})) # True: nothing in common
print({1, 2} == {2, 1}) # True: order does not matter
Two sets are equal if they have exactly the same elements, regardless of the order in which they were written.
Example: guests at two parties
party1 = {"ana", "luis", "eva"}
party2 = {"luis", "eva", "marta"}
print(sorted(party1 & party2)) # ['eva', 'luis']
print(sorted(party1 - party2)) # ['ana']
print(sorted(party1 | party2)) # ['ana', 'eva', 'luis', 'marta']
Practice in Common elements, Same letters and Guest lists.