CurriculumChoosing Python Data Structures, for KidsSets: no duplicates, fast membership

Python Sets Explained: No Duplicates, Fast Membership Checks

The one structure whose whole job is 'no repeats' — and the one honest limit that comes with it.

Lesson 3 of 4PROAges 10+
See what PRO unlocks →

Sets: no duplicates, fast membership

Lists, dicts, and now one more: a set. Its whole job is simple — no duplicates, ever, and fast 'is this in here' checks.

set(a_list) throws away every duplicate automatically. 6 visits, but only 3 different rooms.

visited = ['cave', 'forest', 'cave', 'lake', 'forest', 'cave']
unique_rooms = set(visited)
print(len(unique_rooms))

Output

3

You can also write a set directly with curly braces — {} — same symbol as a dict, but with values only, no keys.

allowed = {'sword', 'shield', 'bow'}
print('axe' in allowed)

Output

False

One real limit, worth knowing rather than discovering the hard way: a set has NO guaranteed order.

Printing a set directly can show its items in any order — not wrong, just unpredictable. sorted() fixes that when you actually need a real order.

tags = ['fire', 'ice', 'fire', 'poison']
unique_tags = set(tags)
print(sorted(unique_tags))

Output

['fire', 'ice', 'poison']

Rule of thumb: reach for a set when the question is 'how many different things' or 'is this one of them' — and convert to a sorted list the moment order matters.

Check your understanding

visited = ['cave', 'forest', 'cave', 'lake']. What does len(set(visited)) give you?

print(len(set(visited)))
  • 3 — cave, forest, and lake are the only DIFFERENT rooms
  • 4 — the same as len(visited), since converting to a set doesn't remove anything

Why: 3. set(visited) collapses the two 'cave' entries into one — a set can never contain the same value twice. cave, forest, and lake are the only genuinely different rooms, even though the original list mentions 4 visits.

unique_tags = set(['fire', 'ice', 'poison']). What's true about print(unique_tags)'s order?

  • The order isn't guaranteed — it might not match the order the items were added in
  • It always prints in the same order they were added, just like a list

Why: Not guaranteed. A set is built for fast membership checks, not for remembering insertion order the way a list does — printing it directly can come out in a different order than you added things. sorted() is the fix whenever the order actually matters.

What you'll practice

visited = ['cave', 'forest', 'cave', 'lake', 'forest', 'cave'] — the dragon revisited some rooms. How many DIFFERENT rooms did it actually visit, not counting repeats? Turn the list into a set with set(visited), then print how many items it has.

Unlock this lesson with PRO →

More from this topic

Sets: no duplicates, fast membership is one lesson inside Choosing Python Data Structures, for Kids — see the full lesson order and what the whole topic covers.

View the full topic →