Combining sets: | & - ^
🌍 In real life. A school has a chess club and an art club. The head teacher asks: "Who's in both clubs?", "Who's in at least one?", "Who's in chess but not art?" Drawing two overlapping circles, a Venn diagram, answers every one of those questions at a glance.
Python's set operators are that diagram in code.
The idea in one sentence: four operators combine two sets into a new set, choosing from the left circle, the right circle, or the overlap.
Its words:
a | b(union): everything in either seta & b(intersection): only what's in botha - b(difference): what's inabut not inba ^ b(symmetric difference): what's in exactly one of them
Step by step, for chess & art:
- Sort each name into "chess only", "both" or "art only": Cy is in both.
&keeps only the middle part.- The result is a new set,
{'Cy'};chessandartare unchanged.
chess = {"Ana", "Bo", "Cy"}
art = {"Cy", "Di"}
print(sorted(chess & art))
print(sorted(chess | art))chess = {"Ana", "Bo", "Cy"}
art = {"Cy", "Di"}
print(sorted(chess - art))
print(sorted(art - chess))
print(sorted(chess ^ art))The same operators work for numbers:
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(sorted(a ^ b))
print(len(a | b))What it costs. Each operator walks the sets once, checking each value against the other set with a fast hash lookup. So a & b takes about as many steps as there are values, not values × values, as a nested loop over two lists would.
Mistakes and edge cases.
- + for joining sets.
{1} + {2}givesTypeError: unsupported operand type(s) for +: 'set' and 'set'. Use|. - The order of -.
a - bandb - aare different sets;|,&and^don't care about order. - Expecting a or b to change. The operators make a new set. To change
aitself, writea |= bora &= b. - Mixing up & and |. "In both" is
&; "in either" is|.
Quiz
What does this print?
a = {1, 2, 3} b = {2, 3, 4} print(sorted(a & b))What does this print?
print(sorted({1, 2} | {2, 5}))What does this print?
print(sorted({1, 2, 3} - {2}))Which operator gives the items that are in exactly one of the two sets?
- ^
- &
- |
What does this print?
a = {1, 2} b = {1, 2} print(len(a ^ b))This should print only the values that are in both sets, {2}. Which line has the mistake?
a = {1, 2} b = {2, 3} both = a | b print(both)
Coding tasks
Ask for two lines of words. Print the words that are on both lines, in alphabetical order, one per line.
Ask for two lines of whole numbers. On the first output line, print the sorted list of numbers that are only on the first line. On the second, the sorted list of numbers only on the second line. For
1 2 3and2 4 6, print[1, 3]then[4, 6].Ask for the jewel letters (like
aA), then for your stones (likeaAAbbbb). Each letter is one stone. Print how many of your stones are jewels. Capital and small letters are different.