Sets
A set is a bag of unique items.
If you drop in two of the same thing, only one stays.
Sets do not keep a fixed order like a neat shelf.
They are great for membership checks and removing copies.
Creating a set
Use curly braces with values, or use set().
An empty set must be set(), because {} makes an empty dict.
Add and remove
add puts one item in.
remove takes one out and errors if missing.
discard takes one out and stays quiet if missing.
Membership
Ask if an item is in the bag with in.
This is fast and easy to read.
Set math
Sets can combine like groups of stickers.
union: everything from both bags
intersection: only items in both bags
difference: items in the first bag but not the second
symmetric_difference: items in one bag or the other, not both
Removing duplicates from a list
Turn a list into a set, then back into a list.
Order may change. That is okay when order does not matter.
When to use a set
Use a set when uniqueness matters.
Use a list when order and duplicates matter.
Use a dict when each item needs a label and a value.
Tip: Remember {} is an empty dict. Use set() when you need an empty set.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.