Python Sets: Unique Items, Fast Membership, and Set Operations
A Python set is an unordered collection of unique items. Use it when you need fast membership checks, want to remove duplicates, or need set math like union, intersection, and difference. This article shows how sets work, how to use them correctly, and the mistakes that often confuse beginners.
Difficulty: Beginner
Helpful to know first: basic variables, lists, and how for loops and if statements work in Python.
How Python Sets Store Unique Values
A set keeps only one copy of each value. If you add the same value more than once, Python stores it only once. This makes sets useful when you care about whether something is present, but not about the order of items.
Here is the smallest useful example:
fruits = {"apple", "banana", "apple"}
print(fruits)
# Output: {'apple', 'banana'}The duplicate "apple" is removed automatically. The exact display order can vary, because sets do not preserve a meaningful order the way lists do.
A set can hold numbers, strings, and other immutable values. It cannot hold mutable items like lists or dictionaries, because set elements must be hashable. That rule is what makes fast lookup possible.
Creating a Set in Python
You can create a set with curly braces, but only when the braces contain at least one item. An empty pair of braces creates a dictionary, not a set. To make an empty set, use set().
colors = {"red", "green", "blue"}
empty_set = set()
not_a_set = {}
print(type(colors).__name__, type(empty_set).__name__, type(not_a_set).__name__)
# Output: set set dictYou can also build a set from any iterable, such as a list, tuple, or string. Python removes duplicates during the conversion.
numbers = set([1, 2, 2, 3, 3, 3])
print(numbers)
# Output: {1, 2, 3}Adding, Removing, and Checking Items in a Set
Most set work is about three actions: add an item, remove an item, or ask whether an item is present. Sets are especially good at membership checks, which use the in operator.
Adding one value at a time
Use add() to insert one item. If the item already exists, nothing changes.
languages = {"Python", "JavaScript"}
languages.add("Rust")
languages.add("Python")
print(languages)
# Output: {'Python', 'JavaScript', 'Rust'}The second add() call does not create a duplicate. That behavior is one of the main reasons to use a set instead of a list.
Removing values safely
Use remove() when the item should be there. Use discard() when the item may or may not be there.
bag = {"pen", "pencil", "eraser"}
bag.remove("pencil")
bag.discard("marker")
print(bag)
# Output: {'pen', 'eraser'}If you use remove() on a missing item, Python raises KeyError. discard() avoids that error and is often safer in cleanup code.
Checking membership quickly
The expression value in my_set asks whether the set contains a value. This is usually one of the fastest operations in Python for large collections.
allowed_roles = {"admin", "editor", "viewer"}
print("admin" in allowed_roles)
print("guest" in allowed_roles)
# Output:
# True
# FalseThat check is often clearer and faster than searching through a list with a loop.
Real-World Ways to Use Python Sets
Sets are not just for toy examples. They are a practical tool for duplicate removal, comparisons between groups, and quick membership tests in real programs.
Removing duplicate items from a list
If you only need the unique values from a list and do not care about order, converting to a set is the shortest solution.
tags = ["python", "data", "python", "code"]
unique_tags = set(tags)
print(unique_tags)
# Output: {'python', 'data', 'code'}Remember that the output order is not guaranteed. If you need the unique values in a stable order, keep reading for a safer pattern later in this article.
Finding shared items between two groups
Use & or intersection() to find values shared by both sets.
course_a = {"Ana", "Ben", "Cara"}
course_b = {"Ben", "Cara", "Drew"}
shared = course_a & course_b
print(shared)
# Output: {'Ben', 'Cara'}Intersection is useful for permissions, overlapping tags, and matching records between two datasets.
Finding values that are only in one set
Use difference to remove items found in another set. This is useful when you want to know what is missing.
all_students = {"Ava", "Noah", "Mia", "Liam"}
present_today = {"Ava", "Mia"}
print(all_students - present_today)
# Output: {'Noah', 'Liam'}Difference answers the question, “What is in the first set but not the second?”
Combining all unique values
Use union to combine both sets without duplicates.
team_one = {"red", "blue"}
team_two = {"blue", "green"}
print(team_one | team_two)
# Output: {'red', 'blue', 'green'}Union keeps every unique value from both sets. Like other set results, the order is not meaningful.
How Set Operations Work Under the Hood
Sets are implemented with a hash table. Each item must be hashable, which means Python can use a stable hash value to place and find the item quickly. That is why membership checks are often fast, even for large sets.
Because of this design, sets have a few important behaviors:
- Items must be immutable or otherwise hashable, such as int, str, and tuple with hashable contents.
- Two equal values are treated as the same element.
- The order of iteration is not a language feature you should rely on.
If you only need to test membership, a set is often a better choice than a list. If you need the original order, use a list or keep a separate ordered structure.
Here is a simple example that shows order is not a promise:
items = {3, 1, 2}
for item in items:
print(item)
# Output:
# 1
# 2
# 3That output may look sorted here, but you should not treat it as sorted behavior. A different program run, different values, or different Python details can produce a different order.
Predict the Output
Read each snippet carefully. Sets often trip people up because duplicates disappear and order is not the same as input order.
Duplicate values in a set literal
What does this print?
letters = {"a", "b", "a"}
print(len(letters))Show answer
The set stores only unique values, so "a" appears once and "b" appears once. The length is 2.
# Output: 2Membership after removing an item
What happens here?
people = {"Ada", "Grace"}
people.discard("Ada")
print("Ada" in people)Show answer
discard() removes "Ada" if it exists and does nothing else. After the removal, the membership test is false.
# Output: FalseCommon Mistakes with Python Sets
Using curly braces for an empty set
Beginners often write {} when they want an empty set. In Python, that creates a dictionary instead.
Problem: The code creates a dictionary, so set methods like add() are not available.
items = {}
items.add(1)
# AttributeError: 'dict' object has no attribute 'add'Fix: Use set() for an empty set.
items = set()
items.add(1)
print(items)
# Output: {1}The corrected version works because set() creates the right type.
Trying to store a mutable value in a set
Set elements must be hashable. Lists are mutable, so they cannot be added to a set.
Problem: A list cannot be hashed, so Python raises a TypeError when you try to insert it into a set.
groups = set()
groups.add([1, 2])
# TypeError: unhashable type: 'list'Fix: Use an immutable value such as a tuple, if that matches your data model.
groups = set()
groups.add((1, 2))
print(groups)
# Output: {(1, 2)}The tuple works because it is immutable and hashable.
Assuming sets keep the original order
Converting a list to a set removes duplicates, but it does not preserve list order as part of the set's behavior.
Problem: The program prints a set, not a list, so the order can surprise you and should not be used for display logic that depends on sequence.
names = ["Mia", "Noah", "Mia"]
unique_names = set(names)
print(unique_names)Fix: If you need unique values in first-seen order, track what you have seen while building a list.
names = ["Mia", "Noah", "Mia"]
seen = set()
unique_names = []
for name in names:
if name not in seen:
seen.add(name)
unique_names.append(name)
print(unique_names)
# Output: ['Mia', 'Noah']The corrected version keeps the original sequence while still using a set for fast membership checks.
Find the Bug
This code tries to keep unique student names, but it has a subtle bug. Find it before looking at the answer.
students = {"Ava", "Ben", "Ava"}
students.append("Cara")
print(students)Show answer
The bug is that sets do not have an append() method. That method belongs to lists. A set uses add() to insert one item.
Fixed code:
students = {"Ava", "Ben", "Ava"}
students.add("Cara")
print(students)
# Output: {'Ava', 'Ben', 'Cara'}The fixed version works because add() is the correct method for sets.
When to Use a Set Instead of Another Collection
Use a set when uniqueness and membership speed matter more than order. Use a list when order matters, duplicates matter, or you need indexing.
| Need | Use | Why |
|---|---|---|
| Check whether a value exists | Set | Fast membership testing |
| Keep duplicates | List | Lists allow repeated values |
| Keep order and look up by index | List | Sets do not support indexing |
| Represent an unordered unique group | Set | Matches the data model directly |
Sometimes a dictionary is also a better choice. If you need unique keys paired with values, a dictionary is a better fit than a set.
A common pattern is to use both: a list for the order you want to show, and a set for the values you have already seen.
Set versus list for membership
This example shows why a set is often preferred for repeated membership tests:
allowed = {"red", "blue", "green"}
choice = "blue"
if choice in allowed:
print("allowed")
else:
print("blocked")
# Output: allowedWith a list, the same check still works, but a set is usually the better structure when the collection is only used for membership.
Interview Questions About Python Sets
Why are sets faster for membership checks than lists?
Sets are built on a hash table. Python can usually find a value by its hash instead of scanning every item one by one, so membership tests are often faster than linear list searches.
Why does {} create a dictionary and not a set?
Python uses curly braces for both dictionaries and non-empty set literals. An empty pair of braces would be ambiguous, so Python makes {} a dictionary and uses set() for an empty set.
Can a set contain another set?
No. A normal set is mutable, so it cannot be stored inside another set. If you need an immutable set-like value inside a set, use frozenset.
Try It Yourself
Create a set of course names, add one new course, remove one old course, and print whether "Math" is still in the set.
- Start with the courses "Math", "Science", and "Art".
- Add "Music".
- Remove "Art".
- Print the final set and then print whether "Math" is in it.
Expected output:
{'Math', 'Science', 'Music'}
TrueHint: Use add() to insert one item, discard() to remove an item safely, and in to test membership.
Show solution
courses = {"Math", "Science", "Art"}
courses.add("Music")
courses.discard("Art")
print(courses)
print("Math" in courses)
# Output:
# {'Math', 'Science', 'Music'}
# TrueSummary
- A set stores unique values and removes duplicates automatically.
- Use set() for an empty set; {} creates a dictionary.
- Use add(), remove(), and discard() to manage items.
- Use in for fast membership tests.
- Use set operations like union, intersection, and difference to compare groups.
- Only hashable values can be stored in a set.
Next, study frozenset if you need an immutable version of a set, or compare sets with lists and dictionaries to choose the right collection for each job.