Module 04 · Lesson 02
Set Creation & Deduplication
Keep only unique values with sets: remove duplicates, test membership quickly, combine groups with union, intersection and difference, and see how sets and dictionary keys relate.
- About 8 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- Remove repeats
- Check with in
- Combine with & and |
- Watch two clubs compare
Each value only once
A set is a bag of values where nothing appears twice. It is great for removing repeats and for quick "is it there?" checks.
Unique
{1, 2, 2, 3}keeps 1, 2 and 3. Repeats simply disappear.No positions
A set has no first or last item, so there is no
[0]. Useinto check for a value.Add and remove
add()puts a value in,discard()takes it out with no error if it is missing.Combine
a | bis everything,a & bis what both share,a - bis what onlyahas.
Sets at work
Any time the question is "who or what, without repeats?", think set.
- UsernamesA sign-up page checks the set of taken names before you pick one.
- BadgesCollecting the same badge twice still counts as one badge.
- Friends in common
mine & yoursshows the friends two people share. - TagsA post's tags are a set: adding #python twice still shows it once.
Repeats disappear
This line turns a list with repeats into a set. Tap each part to see its job.
Part 1 of 2
make a set:set() builds a set from anything with items in a row, dropping every repeat.
Prints {1, 2, 3}
Keep only one of each
Pick an example, change it, then press Run. Say what you expect to see before you press. Sets of words print in a changing order, so these use `sorted()` to show them.
Example 1 of 6Remove repeats
Turn a list into a set and the repeats are gone.
Your turn: Add more rolls until all six numbers have come up.
rolls = [6, 2, 6, 3, 2, 6, 1] unique = set(rolls) print(unique) print(len(rolls), "rolls,", len(unique), "different numbers")
Press Run to see what it prints.Watch two clubs compare lists
Press Step to run one line at a time. The numbers are pupil ticket numbers from two clubs.
Ready. Press Step to run the first line.
- chess = {1, 2, 3, 4}
- art = {3, 4, 5}
- both = chess & art
- either = chess | art
- only_chess = chess - art
- print(both)
- print(len(either), only_chess)
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.How many are left?
print(len({1, 1, 2, 2, 2}))0 of 6 answered
Common set misconceptions
Each card is something beginners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
s = {1, 2, 3} s = set() s = set(items) # set() is empty
s.add(x) s.remove(x) s.discard(x) x in s
a | b a & b a - b a ^ b # union, both, only a, exactly one
a <= b a >= b a.isdisjoint(b) a == b
sorted(s) # order for display
order - stock.keys() # dictionary keys act like a setPress Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
Unique words in a message
Count how many different words a message uses, ignoring case, and list them in alphabetical order.
message = "the cat saw the other cat and the dog"
words = message.lower().split()
unique = set(words)
print("Words:", len(words))
print("Different words:", len(unique))
print(sorted(unique))Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
Using {} for an empty set
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
seen = {}
seen.add(5)Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Events
Checking a guest list at the door
A birthday party has an invitation list. As guests arrive, the host checks each name and records arrivals, making sure nobody is counted twice.
Why Python fits
One set holds the fixed invitations and another grows as people arrive. Membership tests decide each case, and a difference reports who is still to come.
Pythoninvited = {"Ana", "Bo", "Cy", "Dee"} arrived = set() for name in ["Bo", "Ana", "Zed", "Bo"]: if name not in invited: print(f"{name}: not on the list") elif name in arrived: print(f"{name}: already here") else: arrived.add(name) print(f"{name}: welcome") print("Still to come:", sorted(invited - arrived))OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
Why does my set print in a strange order?
How do I remove duplicates but keep the original order?
Can a set hold lists?
Is a set always faster than a list?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 6 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.