Python Sets
Learn how Python sets store unique values, remove duplicates, perform mathematical set operations, and solve real-world data comparison problems.
Learning Objectives
By the end of this lesson, you will be able to:
- Understand what Python sets are and why they are useful.
- Create sets and understand their unique-value behavior.
- Add and remove elements from sets.
- Use membership testing efficiently.
- Perform union, intersection, difference, and symmetric difference operations.
- Understand subsets, supersets, and disjoint sets.
- Use sets to solve practical data-cleaning and comparison problems.
-
Understand the difference between
setandfrozenset.
What Are Sets?
A set is a Python collection used to store multiple unique values.
Unlike lists and tuples, sets do not maintain a meaningful positional order for accessing individual elements.
The most important characteristic of a set is that duplicate values are automatically removed.
numbers = {1, 2, 3, 4}
print(numbers)
Sets are particularly useful when we care about whether a value exists rather than where it appears.
Think of a set as a collection where every value can appear only once.
Why Sets Matter
Sets are extremely useful when working with unique values and comparing groups of data.
Imagine a website receiving the same email address multiple times:
emails = [
"ali@example.com",
"sara@example.com",
"ali@example.com",
"ahmed@example.com"
]
We can use a set to quickly obtain unique email addresses:
unique_emails = set(emails)
print(unique_emails)
This makes sets especially valuable in data processing, analytics, databases, permissions, tags, and comparison tasks.
Creating Sets
Sets are commonly created using curly braces
{}.
fruits = {"apple", "banana", "mango"}
numbers = {10, 20, 30}
colors = {"red", "green", "blue"}
Sets can also be created from other iterable objects
using set().
numbers = set([1, 2, 3, 4])
print(numbers)
Sets Automatically Remove Duplicates
If the same value appears multiple times in a set, Python keeps only one occurrence.
numbers = {1, 2, 2, 3, 3, 3, 4}
print(numbers)
{1, 2, 3, 4}
This makes sets a convenient way to remove duplicate values from a list.
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = list(set(numbers))
print(unique_numbers)
Converting a list to a set removes duplicates, but it also means you should not rely on the resulting set preserving the original list order.
Sets Are Unordered
Sets are not sequences like strings, lists, and tuples. You should not use numeric indexes to access set elements.
colors = {"red", "green", "blue"}
print(colors[0])
This raises a TypeError because sets
do not support indexing.
Use sets when uniqueness and membership matter. Use lists or tuples when positional order matters.
Creating an Empty Set
This is an important Python detail.
Although curly braces are used for non-empty sets,
{} creates an empty dictionary.
empty = {}
print(type(empty))
<class 'dict'>
To create an empty set, use set().
empty_set = set()
print(type(empty_set))
<class 'set'>
Adding Items to a Set
The add() method adds one value to a set.
fruits = {"apple", "banana"}
fruits.add("mango")
print(fruits)
If the value already exists, adding it again does not create a duplicate.
numbers = {1, 2, 3}
numbers.add(3)
print(numbers)
The set still contains only one 3.
Adding Multiple Items
The update() method adds multiple values
from another iterable.
numbers = {1, 2, 3}
numbers.update([4, 5, 6])
print(numbers)
Unlike add(), which adds one element,
update() can add multiple elements.
add() vs update()
add() adds one element.
update() adds elements from
another iterable.
Removing Items
Python provides several ways to remove set elements.
remove()
Removes a specified element. If the element does not
exist, Python raises a KeyError.
fruits = {"apple", "banana", "mango"}
fruits.remove("banana")
print(fruits)
discard()
discard() also removes an element, but
does nothing if the element does not exist.
fruits = {"apple", "banana"}
fruits.discard("orange")
print(fruits)
No error occurs because "orange" was not
present.
pop()
pop() removes and returns an arbitrary
element from a set. Because sets are unordered,
you should not assume which element will be removed.
numbers = {10, 20, 30}
removed = numbers.pop()
print("Removed:", removed)
print("Remaining:", numbers)
clear()
clear() removes all elements.
numbers = {1, 2, 3}
numbers.clear()
print(numbers)
set()
Membership Testing
Sets are especially useful for membership testing.
users = {"Ali", "Sara", "Ahmed"}
print("Ali" in users)
print("John" in users)
print("John" not in users)
True
False
True
This makes sets particularly useful for checking whether something belongs to a collection of unique values.
Finding Set Length
Use len() to find the number of unique
elements in a set.
numbers = {10, 20, 30, 40}
print(len(numbers))
4
Union
The union of two sets contains all unique elements from both sets.
We can use the | operator or
union() method.
a = {1, 2, 3}
b = {3, 4, 5}
result = a | b
print(result)
{1, 2, 3, 4, 5}
The duplicate value 3 appears only once.
a = {1, 2, 3}
b = {3, 4, 5}
result = a.union(b)
print(result)
Intersection
The intersection contains only the values that exist in both sets.
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
result = a & b
print(result)
{3, 4}
Only 3 and 4 are present in
both sets.
result = a.intersection(b)
print(result)
Difference
The difference between two sets contains elements that exist in the first set but not the second.
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a - b)
{1, 2}
Values 1 and 2 exist in
a but not in b.
Reversing the operation gives a different result:
print(b - a)
{5, 6}
Symmetric Difference
Symmetric difference returns elements that exist in either set, but not in both.
The operator is ^.
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a ^ b)
{1, 2, 5, 6}
The shared values 3 and 4
are excluded.
Subsets & Supersets
A set is a subset of another set if every element in the smaller set is also present in the larger set.
a = {1, 2}
b = {1, 2, 3, 4}
print(a.issubset(b))
True
We can also use the <= operator.
print(a <= b)
A superset is the opposite relationship.
print(b.issuperset(a))
True
Disjoint Sets
Two sets are disjoint when they have no elements in common.
a = {1, 2, 3}
b = {4, 5, 6}
print(a.isdisjoint(b))
True
If even one value is shared, the result becomes
False.
Looping Through Sets
Sets are iterable, so we can use a
for loop to process their elements.
colors = {"red", "green", "blue"}
for color in colors:
print(color)
Remember that the iteration order of a set should not be relied upon.
If your program requires a predictable sequence, use a list or another ordered data structure.
Frozenset
A frozenset is an immutable version of a set.
Once a frozenset is created, its elements cannot be added or removed.
numbers = frozenset([1, 2, 3, 4])
print(numbers)
Because it is immutable, it does not provide methods
such as add() or remove().
When Is Frozenset Useful?
Frozensets are useful when you need a fixed set of unique values and want the collection to be immutable.
Practical Real-World Examples
Example 1 — Removing Duplicate User IDs
user_ids = [
101,
102,
101,
103,
102,
104
]
unique_ids = set(user_ids)
print(unique_ids)
The set gives us only the unique user IDs.
Example 2 — Comparing Course Students
python_students = {"Ali", "Sara", "Ahmed", "Hina"}
sql_students = {"Sara", "Ahmed", "Usman"}
both_courses = python_students & sql_students
print(both_courses)
{'Sara', 'Ahmed'}
The intersection identifies students enrolled in both courses.
Example 3 — Website Permissions
user_permissions = {
"read",
"write",
"download"
}
if "delete" in user_permissions:
print("Delete access granted.")
else:
print("Delete access denied.")
Delete access denied.
Example 4 — Finding Common Skills
developer_a = {
"Python",
"SQL",
"Power BI",
"Excel"
}
developer_b = {
"Python",
"SQL",
"JavaScript"
}
common_skills = developer_a & developer_b
print(common_skills)
{'Python', 'SQL'}
Common Set Mistakes
Mistake 1 — Expecting Indexing
colors = {"red", "green", "blue"}
print(colors[0])
Sets do not support indexing.
Mistake 2 — Confusing {} with an Empty Set
empty = {}
print(type(empty))
This creates an empty dictionary.
Correct:
empty = set()
Mistake 3 — Using remove() Without Checking
numbers = {1, 2, 3}
numbers.remove(10)
This raises a KeyError.
If you want to safely ignore a missing value, use
discard().
Mistake 4 — Assuming Set Order
colors = {"red", "green", "blue"}
for color in colors:
print(color)
Do not write programs that depend on the order in which set elements are displayed or iterated.
Mistake 5 — Expecting Duplicates
numbers = {1, 1, 2, 2, 3, 3}
print(numbers)
Sets automatically eliminate duplicate values.
Practice Exercises
Exercise 1 — Create a Set
Create a set containing five programming languages and print it.
Exercise 2 — Remove Duplicates
Create a list containing duplicate numbers and convert it into a set to obtain unique values.
Exercise 3 — Add and Remove
Create a set of five fruits. Add another fruit and remove one existing fruit.
Exercise 4 — Membership
Create a set of programming languages and check whether Python exists in it.
Exercise 5 — Union
Create two sets of numbers and find all unique numbers from both sets.
Exercise 6 — Intersection
Create two sets of student names and find the students who are present in both.
Exercise 7 — Difference
Create two sets of skills and find the skills available in the first set but not the second.
Exercise 8 — Symmetric Difference
Create two sets and find values that belong to only one of the sets.
Mini Challenge — Course Enrollment Analyzer
Imagine that a training institute has students enrolled in two different courses.
Build a program that determines:
- Students enrolled in Python.
- Students enrolled in SQL.
- Students enrolled in both courses.
- Students enrolled only in Python.
- Students enrolled only in SQL.
- The total number of unique students.
python_students = {
"Ali",
"Sara",
"Ahmed",
"Hina",
"Usman"
}
sql_students = {
"Sara",
"Ahmed",
"Usman",
"Ayesha"
}
# Students in both courses
both = python_students & sql_students
# Only Python
only_python = python_students - sql_students
# Only SQL
only_sql = sql_students - python_students
# All unique students
all_students = python_students | sql_students
print("Both:", both)
print("Only Python:", only_python)
print("Only SQL:", only_sql)
print("Total Students:", len(all_students))
Try modifying the student names and experiment with different set operations. This challenge combines several important set concepts into one practical problem.
Quick Knowledge Check
1. What is the main characteristic of a Python set?
2. Which brackets are commonly used for a non-empty set?
3. How do you create an empty set?
4. Which method adds one element to a set?
5. What does the & operator
perform between sets?
6. What does a | b produce?
7. Which method safely removes an item without raising an error if it does not exist?
8. Can you access a set element using
my_set[0]?
9. What does a - b return?
10. What is a frozenset?
Lesson Summary
Python sets are powerful collection objects designed primarily for storing unique values and comparing groups of data.
- Sets store unique values.
- Duplicate values are automatically removed.
- Sets do not support indexing.
-
Use
set()to create an empty set. -
add()adds one element. -
update()adds multiple elements. -
remove()removes a specific value and raises an error if it is missing. -
discard()removes a value without raising an error if it is missing. -
clear()removes all elements. -
inandnot inperform membership testing. -
|performs union. -
&performs intersection. -
-performs difference. -
^performs symmetric difference. -
issubset()checks subset relationships. -
issuperset()checks superset relationships. -
isdisjoint()checks whether two sets have no common elements. -
frozensetprovides an immutable set.
Use a set when uniqueness, membership testing, or comparing groups of values is important. Sets become especially powerful when working with real-world data cleaning, permissions, tags, users, and analytics.
Ready for the Next Lesson?
You've learned how Python sets store unique values and how set operations can solve practical data comparison problems.