Using Sets in Your Code
The idea
You know what a set is and why it exists.
Now let's look at what you can actually do with one — adding, removing, checking, and comparing.
Adding and removing elements
add() adds one element. If it already exists — nothing happens.
squad = {"Raven", "Wolf", "Ghost"}
squad.add("Viper")
squad.add("Raven") # already there — ignored
print(squad)
Output → {'Ghost', 'Raven', 'Viper', 'Wolf'}
remove() removes an element — raises KeyError if not found.
discard() removes an element — silently does nothing if not found.
squad.remove("Wolf") # KeyError if missing
squad.discard("Fox") # no error if missing
pop() removes and returns a random element — sets are unordered, so you don't control which one.
removed = squad.pop()
print(removed) # unpredictable — could be any element
clear() empties the set.
Checking membership
in works the same as with lists — but faster:
squad = {"Raven", "Wolf", "Ghost"}
print("Wolf" in squad) # True
print("Fox" in squad) # False
Set operations — where sets shine
Sets support mathematical operations that lists don't.
Union — all elements from both sets, no duplicates:
alpha = {"Raven", "Wolf", "Ghost"}
bravo = {"Ghost", "Viper", "Bull"}
print(alpha | bravo)
Output → {'Bull', 'Ghost', 'Raven', 'Viper', 'Wolf'}
Intersection — only elements that appear in both:
print(alpha & bravo)
Output → {'Ghost'}
Difference — elements in the first but not the second:
print(alpha - bravo)
Output → {'Raven', 'Wolf'}
Symmetric difference — elements in either set, but not both:
print(alpha ^ bravo)
Output → {'Bull', 'Raven', 'Viper', 'Wolf'}
Checking relationships
a = {1, 2, 3}
b = {1, 2, 3, 4, 5}
print(a.issubset(b)) # True — all of a is in b
print(b.issuperset(a)) # True — b contains all of a
print(a.isdisjoint({4, 5})) # True — no elements in common
Useful patterns
Deduplicate a list and get it back as a list:
names = ["Raven", "Wolf", "Raven", "Ghost", "Wolf"]
unique = list(set(names))
print(unique)
Find common elements between two lists:
list1 = ["Raven", "Wolf", "Ghost"]
list2 = ["Ghost", "Viper", "Bull"]
common = set(list1) & set(list2)
print(common)
Output → {'Ghost'}
Heads up!
remove()raisesKeyErrorif missing — usediscard()when unsurepop()on a set removes a random element — don't rely on order- Set operations return new sets — the originals are unchanged
- You can't index a set — convert to list first if you need positional access
What you should understand now
add()adds one element — duplicates ignoreddiscard()removes safely —remove()raises an error if missinginchecks membership — fast|union,&intersection,-difference,^symmetric difference- Set operations return new sets — originals unchanged