Data Structures16 min read
Set Basics
Learn sets from scratch: uniqueness, fast membership checks, and practical use cases like removing duplicates and comparing groups of data.
David Miller
November 21, 2025
2.9k139
A set stores unique items and is usually unordered.
Why sets matter
Sets are extremely useful when you want:
- remove duplicates
- check membership fast
- compare groups (common vs missing)
Create a set
nums = {1, 2, 3, 3, 3}
print(nums) # {1,2,3} duplicates removed
Add and remove
s = {"a", "b"}
s.add("c")
s.remove("b") # error if missing
s.discard("x") # safe if missing
Fast membership
users = {"Tom", "Sarah", "Mike"}
print("Sarah" in users) # fast
Common set operations (very useful)
a = {"Tom", "Sarah", "Mike"}
b = {"Sarah", "Ahsan"}
print(a & b) # intersection -> common
print(a | b) # union -> all
print(a - b) # difference -> in a not in b
Real example: find new applicants
applied = {"Tom", "Sarah"}
all_users = {"Tom", "Sarah", "Mike", "Ahsan"}
not_applied = all_users - applied
print(not_applied)
Graph: set uniqueness
flowchart LR
A[Input: a,a,b,c] --> B[Set]
B --> C[Output: a,b,c]
Remember
- Sets remove duplicates automatically
- Use sets for fast membership
- Set operations solve many real problems
#Python#Beginner#Set