Sets
Collections with no duplicates. Find what two groups share.
Code runs right here in your browser. Nothing to install.
Learn it
A set holds unique items. & finds what two sets share.
A set is an unordered collection with no duplicates. Make one with curly brackets: {1, 2, 3}, or turn a list into a set with set(my_list) to remove repeats instantly. An empty set is set() because {} makes an empty dictionary.
Sets have no positions, so no indexing. Add with .add(x), remove with .discard(x), and check membership with in (which is very fast).
Set maths: a | b is the union (everything in either), a & b is the intersection (in both), and a - b is the difference (in a but not b).
visits = ["park", "shop", "park", "cafe", "shop"] places = set(visits) print(sorted(places)) alex = {"chess", "coding", "football"} sam = {"coding", "art", "football"} print(sorted(alex & sam)) print(sorted(alex | sam)) print(sorted(alex - sam))
Try it yourself
+10 XPTurn the guesses list into a set to find the unique guesses, then print how many unique guesses there were: Unique guesses: 4.
Create a free account to start this lab
Sign in to write, run and check your code here. Your progress, XP and code are saved to your account. No card needed.
Capture the flag
+10 XPWhich set operator finds the items that are in BOTH sets? (one symbol)
Create a free account to start this lab
Sign in to answer the flag question. Your progress, XP and code are saved to your account. No card needed.
Friend finder
+20 XPTwo friends list the games they own. Use set operations to print: games they both own, games either owns, and games only kai owns. Print each as a sorted list with labels Both:, Either:, Only Kai:.
Create a free account to start this lab
Sign in to do this homework and have it checked. Your progress, XP and code are saved to your account. No card needed.