01 / 20

Sets for Membership
& Duplicates

Learn how Python's set data structure enables blazing-fast membership testing and effortless duplicate removal: two of the most common tasks in real-world programming.

Python

What Is a Set?

A set is an unordered collection of unique elements. Unlike lists and tuples, sets guarantee that no value appears more than once, and they do not maintain insertion order for iteration purposes.

Unordered
Elements have no index: you cannot access s[0].
Unique
Duplicates are automatically discarded on insertion.
Mutable
You can .add() and .remove() elements after creation.

Creating Sets in Python

# Curly-brace literal colors = {"red", "green", "blue"} # From a list (duplicates removed) nums = set([1, 2, 2, 3, 3, 3]) # nums is now {1, 2, 3} # Empty set (NOT {} which creates a dict) empty = set()

Why Sets Matter

Two of the most frequent tasks in programming are checking if an item exists in a collection and removing duplicates. Sets solve both problems elegantly and efficiently.

Membership Testing
Is this username already taken? Is this word in the dictionary? Sets answer in constant time.
Duplicate Removal
Clean survey responses, deduplicate log entries, or find unique visitors: one line of code.

The Core Rule: \( O(1) \) Lookup

Sets are backed by a hash table. Each element is converted to a hash, which maps directly to a memory bucket. This means the in operator runs in average \( O(1) \) time, regardless of the set's size.

Hash Table Buckets [0] "green" [1] [2] "red" [3] [4] "blue" "red" hash() Bucket [2] Found! O(1)

Set vs List: Membership Speed

Time Number of Elements (\(n\)) 100 1K 10K 100K List: \(O(n)\) Set: \(O(1)\)

Set vs List vs Dict

set list dict
Ordered? No Yes Insertion order
Duplicates? No Yes Keys: No
in speed \(O(1)\) \(O(n)\) \(O(1)\)
Index access No Yes By key
Syntax {a, b} [a, b] {k: v}

Membership Testing: in

banned_users = {"spam_bot", "troll42", "fake_acct"} username = "alice" if username in banned_users: print("Access denied") else: print("Welcome!") # Output: Welcome!

Removing Duplicates

responses = ["yes", "no", "yes", "maybe", "no", "yes"] # Convert to set: duplicates vanish unique = set(responses) # {"yes", "no", "maybe"} # Back to a sorted list if needed unique_list = sorted(unique) # ["maybe", "no", "yes"]

How to Apply Sets

1
Identify the need: Do you need fast lookups or unique elements?
2
Create the set: Use set(iterable) or curly braces {a, b, c}.
3
Test membership: Use x in my_set for \( O(1) \) checks.
4
Modify if needed: Use .add(), .remove(), or .discard().
5
Convert back: Use list(my_set) or sorted(my_set) if you need order.

Example 1: Unique Words

sentence = "the cat sat on the mat the cat" words = sentence.split() # ["the", "cat", "sat", "on", "the", "mat", "the", "cat"] unique_words = set(words) # {"the", "cat", "sat", "on", "mat"} print(len(unique_words)) # 5

Example 2: Common Elements

enrolled_math = {"Alice", "Bob", "Carol", "Dave"} enrolled_sci = {"Bob", "Dave", "Eve", "Frank"} # Students in BOTH classes both = enrolled_math & enrolled_sci # {"Bob", "Dave"} # Students in EITHER class either = enrolled_math | enrolled_sci # {"Alice", "Bob", "Carol", "Dave", "Eve", "Frank"}
Math Science Alice Carol Bob Dave Eve Frank & (intersection)

Example 3: Efficient Search

# Find all IDs present in both logs log_a = [101, 203, 101, 305, 203, 407] log_b = [203, 509, 407, 611, 203] # Step 1: Deduplicate log_b into a set set_b = set(log_b) # {203, 407, 509, 611} # Step 2: Check each unique ID from log_a common = {x for x in log_a if x in set_b} # {203, 407}

Set Operations at a Glance

Operation Operator Method Result
Union a | b a.union(b) All elements
Intersection a & b a.intersection(b) Shared elements
Difference a - b a.difference(b) In a, not in b
Sym. Diff. a ^ b a.symmetric_difference(b) In one, not both

Common Mistakes

✕ Using {} for empty set
{} creates an empty dict, not a set. Use set() instead.
✕ Adding mutable items
Sets require hashable elements. Lists and dicts cannot be added: use tuples instead.
✕ Expecting order
Sets are unordered. Never assume elements come out in the order you put them in.

Question 1 of 5

What is the output of the following code?
print(len(set([3, 1, 4, 1, 5, 9, 2, 6, 5, 3])))

Question 2 of 5

Which expression creates an empty set in Python?

Question 3 of 5

What is the average time complexity of checking x in my_set?

Question 4 of 5

Given a = {1, 2, 3} and b = {2, 3, 4}, what is a & b?

Question 5 of 5

Which of the following cannot be added to a Python set?