Skip to content
Sets and Operations
step 1/7

Reading — step 1 of 7

Learn

~2 min readDictionaries and Sets

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

python

Note: {} is a dictionary literal, NOT a set. To make an empty set, use set().

Adding and removing

python

The four key set operations

Sets shine for relationships between groups. Each operation has both an operator AND a method form:

python

Membership testing — sets vs lists

python

If you'll do many "is X in this collection" checks, convert to a set first.

Deduplication shortcut

python

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

python

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:

python

Common mistakes

  • Using {} for an empty set — it's a dict. Use set().
  • 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…