Create, change and test a set
Sets are printed with sorted(...) here so the order is the same on every run. type(x).__name__ gives the name of x's type as text.
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
distinct colours: 3 ['blue', 'green', 'red']
after changes: ['blue', 'pink', 'red']
blue in colors: True
green in colors: False
unique, sorted: [1, 2, 3]
unique, first-seen order: [3, 1, 2]
{} is a dict | set() is a set