python · level 2 · unit 2 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A keeps exactly one of each value.
A set is a collection that never holds a . Add the same value twice and it is kept once. set(visitors) turns a list into a set, so every repeat vanishes.
A set has no fixed order, so the order it prints in can change from run to run. Pass it to sorted() for a tidy list. .add() puts in one more value, and in checks for one very quickly.
Two sets can be compared: a & b holds what is in both, a | b holds everything from either, and a - b holds what is in a but not in b.
visitors = ["Ana", "Raj", "Ana", "Kim", "Raj"]
unique = set(visitors)
unique.add("Tom")
print(len(unique))
print(sorted(unique))
print("Kim" in unique) An empty set is written set(), because {} makes an empty dictionary.
guess first
Two friends, two playlists. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
maya = {"Hello", "Shake It Off", "Yellow"}
sam = {"Yellow", "Hello", "Angels"}
print(sorted(maya & sam))
print(sorted(maya - sam))
your turn
Your turn. Find the snacks you both like.
Fill in a set of snacks for each friend, with at least one snack in both. Then pick the sign that keeps only the shared snacks.
fix it
The party guest list crashes. Can you fix it?
- Read the error. What kind of value does Python say
guestsis? - Empty curly brackets make an empty dictionary, not an empty set, and dictionaries have no
.add(). - Change line 2 to guests = set(), then run.
nailed it
you kept one of each. :D
- A set holds each value once, in no fixed order.
- Use
sorted()to show a set in a tidy order. &means in both,|means either,-means take away.
new words in your collection
- set
- duplicate
This lesson isn’t saved. A free account remembers every lesson you finish.