A set holds unique values with no order. Python has four operators that combine two sets, the same operations you may know from maths.
The program
python
python_club = {"Ada", "Linus", "Grace", "Alan"}
chess_club = {"Grace", "Alan", "Hedy", "Margaret"}
print("In either club:", sorted(python_club | chess_club))
print("In both clubs: ", sorted(python_club & chess_club))
print("Only Python: ", sorted(python_club - chess_club))
print("Only one club: ", sorted(python_club ^ chess_club))output
In either club: ['Ada', 'Alan', 'Grace', 'Hedy', 'Linus', 'Margaret'] In both clubs: ['Alan', 'Grace'] Only Python: ['Ada', 'Linus'] Only one club: ['Ada', 'Hedy', 'Linus', 'Margaret']
How it works
a | bora.union(b)is the union: everything that is inaorb.a & bora.intersection(b)is the intersection: only what is in both.a - bora.difference(b)is the difference: what is inabut not inb.a ^ bora.symmetric_difference(b)is the symmetric difference: what is in one set but not in both.- A set has no order, and the order Python prints a set of strings in can change from one run to the next.
sorted()turns each result into a list in alphabetical order, so the output is always the same. a - bandb - aare different:chess_club - python_clubwould give Hedy and Margaret.
Methods accept any iterable
The operators need a set on both sides. The method versions also accept a list or tuple:
python
python_club = {"Ada", "Linus", "Grace", "Alan"}
new_members = ["Hedy", "Ada", "Hedy"]
print(sorted(python_club.union(new_members)))output
['Ada', 'Alan', 'Grace', 'Hedy', 'Linus']
Ada and Hedy appear only once in the result, because a set never holds the same value twice.
Related programs: Find common elements of two lists, Union of two lists.