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.
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.
s[0]..add() and .remove() elements after creation.Creating Sets in Python
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.
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.
Set vs List: Membership Speed
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
Removing Duplicates
How to Apply Sets
set(iterable) or curly braces {a, b, c}.x in my_set for \( O(1) \) checks..add(), .remove(), or .discard().list(my_set) or sorted(my_set) if you need order.Example 1: Unique Words
Example 2: Common Elements
Example 3: Efficient Search
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
{} creates an empty dict, not a set. Use set() instead.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])))
len() returns 7.Question 2 of 5
Which expression creates an empty set in Python?
set() and set([]) create empty sets. {} creates an empty dict, not a set. The correct answer is both B and C.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?
& operator computes the intersection: elements present in both sets. The values 2 and 3 appear in both a and b, so the result is {2, 3}.Question 5 of 5
Which of the following cannot be added to a Python set?
TypeError. Tuples, strings, and integers are all hashable and can be added to a set.