Browser lab15 min+60 XP

Sets

Collections with no duplicates. Find what two groups share.

0% done

Code runs right here in your browser. Nothing to install.

TASK 1

Learn it

Key idea

A set holds unique items. & finds what two sets share.

Key words
alexsamchesscodingfootballartalex & sam  gives  coding, footballalex | sam  gives  all four hobbiesalex - sam  gives  chess
Two sets of hobbies, and what the set operators return.

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).

Real life linkA website counting "unique visitors" ignores repeat visits from the same person. A set does that automatically, because it keeps one of each.
Example code
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))
TASK 2

Try it yourself

+10 XP

Turn 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.

TASK 3

Capture the flag

+10 XP

Which 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.

HOMEWORK

Friend finder

+20 XP

Two 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.