Union, intersection, difference and friends
A set is a collection of unique items with no duplicates and no guaranteed order, built on the same hashing as dictionaries. Sets answer "is this in the collection?" very fast and support union, intersection and difference like in school maths.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Given votes = ["a", "b", "a", "c", "b", "a"], print how many different options were voted for and the sorted list of options.
Two friends have watched {"Dune", "Up", "Cars"} and {"Cars", "Coco", "Up"}. Print which films both watched and which films only the first friend watched, each sorted.
Write a loop that goes through [4, 7, 4, 9, 7], prints new: <n> the first time it sees a number and seen: <n> after that.
Explain it without notes
How do you remove duplicates from a list, and what do you lose?
What is the difference between remove and discard on a set?
Why is x in my_set faster than x in my_list?
What is a frozenset and when do you need one?
How do you find the duplicates in a list in O(n) time?
Expected output
either day (|): ['Asha', 'Meena', 'Ravi', 'Tom', 'Zoya']
both days (&): ['Ravi', 'Tom']
only Monday (-): ['Asha', 'Meena']
only Tuesday (-): ['Zoya']
exactly one day (^): ['Asha', 'Meena', 'Zoya']
{1, 2} <= {1, 2, 3}: True
disjoint: True
frozenset key found: 90
words: 8 | unique words: 5
vocabulary: ['and', 'bat', 'cat', 'hat', 'the']