Reading — step 1 of 7
Learn
Imagine you're organizing a party with two guest lists. You need to figure out who's on both, who's only on one, and how many unique people you've invited. A set is an unordered collection of unique elements — no duplicates, no indices, no positions. What sets lack in ordering, they make up for with blazing-fast membership testing (O(1) average).
Creating sets
Note: {} is a dictionary literal, NOT a set. To make an empty set, use set().
Adding and removing
The four key set operations
Sets shine for relationships between groups. Each operation has both an operator AND a method form:
Membership testing — sets vs lists
If you'll do many "is X in this collection" checks, convert to a set first.
Deduplication shortcut
Fastest way to dedupe a list. Caveat: order is lost (sets are unordered). To dedupe AND preserve order: list(dict.fromkeys(words)).
Set requirements — elements must be hashable
Same rule as dict keys — sets internally use hashing.
Frozen sets
If you need a set that CAN be a key in a dict or an element of another set, use frozenset:
Common mistakes
- Using
{}for an empty set — it's a dict. Useset(). - Trying to add a list:
s.add([1, 2])is TypeError. Add a tuple instead:s.add((1, 2)). - Counting on order — sets have NO guaranteed order. If order matters, sort or use a different structure.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…