PythonMastery

Set operations in Python

Union, intersection, difference and symmetric difference of two sets in Python, with the operator and the method name for each.

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

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.

Learn the idea: Sets: Unordered, Unique, Lightning Fast