← All lessons

Set operations

Sign in · Sign up

Lesson 5.8

Sets have three operations:

Operation Meaning
a | b union — all items from both
a & b intersection — only the shared ones
a - b difference — only those in a but not in b
adults = {"Mia", "Timur"}
kids = {"Anna", "Timur"}

print(adults | kids)   # everyone
print(adults & kids)   # Timur
print(adults - kids)   # Mia

The difference depends on the order: kids - adults is Anna. The order in the output of a set is not guaranteed — the check takes that into account.

The lists of friends first and second are set by the check — they are lists, not sets. Turn them into sets with set, then print in order the three operations and the number of shared items with len.

Hint

| is union, & is the shared items, - is what is left of the left one.

First turn both lists into sets with set, otherwise the operations won't work. The order matters in -: first - second and second - first give different results.