Home Course Roadmap
Home / Python Foundations / Lesson 21
Lesson 21 · Data Collections Beginner

Python Sets

Learn how Python sets store unique values, remove duplicates, perform mathematical set operations, and solve real-world data comparison problems.

40–50 minutes Python Foundations Beginner
0%

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 set and frozenset.
01

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.

Python
numbers = {1, 2, 3, 4}

print(numbers)

Sets are particularly useful when we care about whether a value exists rather than where it appears.

Key Idea

Think of a set as a collection where every value can appear only once.

02

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:

Duplicate Data
emails = [
    "ali@example.com",
    "sara@example.com",
    "ali@example.com",
    "ahmed@example.com"
]

We can use a set to quickly obtain unique email addresses:

Remove Duplicates
unique_emails = set(emails)

print(unique_emails)

This makes sets especially valuable in data processing, analytics, databases, permissions, tags, and comparison tasks.

03

Creating Sets

Sets are commonly created using curly braces {}.

Python
fruits = {"apple", "banana", "mango"}

numbers = {10, 20, 30}

colors = {"red", "green", "blue"}

Sets can also be created from other iterable objects using set().

Using set()
numbers = set([1, 2, 3, 4])

print(numbers)
04

Sets Automatically Remove Duplicates

If the same value appears multiple times in a set, Python keeps only one occurrence.

Python
numbers = {1, 2, 2, 3, 3, 3, 4}

print(numbers)
Output
{1, 2, 3, 4}

This makes sets a convenient way to remove duplicate values from a list.

List → Unique Values
numbers = [1, 2, 2, 3, 4, 4, 5]

unique_numbers = list(set(numbers))

print(unique_numbers)
Important

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.

05

Sets Are Unordered

Sets are not sequences like strings, lists, and tuples. You should not use numeric indexes to access set elements.

Invalid Approach
colors = {"red", "green", "blue"}

print(colors[0])

This raises a TypeError because sets do not support indexing.

Remember

Use sets when uniqueness and membership matter. Use lists or tuples when positional order matters.

06

Creating an Empty Set

This is an important Python detail.

Although curly braces are used for non-empty sets, {} creates an empty dictionary.

Empty Dictionary
empty = {}

print(type(empty))
Output
<class 'dict'>

To create an empty set, use set().

Correct Empty Set
empty_set = set()

print(type(empty_set))
Output
<class 'set'>
07

Adding Items to a Set

The add() method adds one value to a set.

add()
fruits = {"apple", "banana"}

fruits.add("mango")

print(fruits)

If the value already exists, adding it again does not create a duplicate.

Duplicate Add
numbers = {1, 2, 3}

numbers.add(3)

print(numbers)

The set still contains only one 3.

08

Adding Multiple Items

The update() method adds multiple values from another iterable.

update()
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.

09

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.

remove()
fruits = {"apple", "banana", "mango"}

fruits.remove("banana")

print(fruits)

discard()

discard() also removes an element, but does nothing if the element does not exist.

discard()
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.

pop()
numbers = {10, 20, 30}

removed = numbers.pop()

print("Removed:", removed)
print("Remaining:", numbers)

clear()

clear() removes all elements.

clear()
numbers = {1, 2, 3}

numbers.clear()

print(numbers)
Output
set()
10

Membership Testing

Sets are especially useful for membership testing.

in / not in
users = {"Ali", "Sara", "Ahmed"}

print("Ali" in users)
print("John" in users)
print("John" not in users)
Output
True
False
True

This makes sets particularly useful for checking whether something belongs to a collection of unique values.

11

Finding Set Length

Use len() to find the number of unique elements in a set.

Python
numbers = {10, 20, 30, 40}

print(len(numbers))
Output
4
12

Union

The union of two sets contains all unique elements from both sets.

We can use the | operator or union() method.

Union Operator
a = {1, 2, 3}

b = {3, 4, 5}

result = a | b

print(result)
Output
{1, 2, 3, 4, 5}

The duplicate value 3 appears only once.

union()
a = {1, 2, 3}
b = {3, 4, 5}

result = a.union(b)

print(result)
13

Intersection

The intersection contains only the values that exist in both sets.

Intersection
a = {1, 2, 3, 4}

b = {3, 4, 5, 6}

result = a & b

print(result)
Output
{3, 4}

Only 3 and 4 are present in both sets.

intersection()
result = a.intersection(b)

print(result)
14

Difference

The difference between two sets contains elements that exist in the first set but not the second.

Difference
a = {1, 2, 3, 4}

b = {3, 4, 5, 6}

print(a - b)
Output
{1, 2}

Values 1 and 2 exist in a but not in b.

Reversing the operation gives a different result:

print(b - a)
Output
{5, 6}
15

Symmetric Difference

Symmetric difference returns elements that exist in either set, but not in both.

The operator is ^.

Symmetric Difference
a = {1, 2, 3, 4}

b = {3, 4, 5, 6}

print(a ^ b)
Output
{1, 2, 5, 6}

The shared values 3 and 4 are excluded.

16

Subsets & Supersets

A set is a subset of another set if every element in the smaller set is also present in the larger set.

Subset
a = {1, 2}

b = {1, 2, 3, 4}

print(a.issubset(b))
Output
True

We can also use the <= operator.

print(a <= b)

A superset is the opposite relationship.

Superset
print(b.issuperset(a))
Output
True
17

Disjoint Sets

Two sets are disjoint when they have no elements in common.

isdisjoint()
a = {1, 2, 3}

b = {4, 5, 6}

print(a.isdisjoint(b))
Output
True

If even one value is shared, the result becomes False.

18

Looping Through Sets

Sets are iterable, so we can use a for loop to process their elements.

Python
colors = {"red", "green", "blue"}

for color in colors:
    print(color)

Remember that the iteration order of a set should not be relied upon.

Do Not Assume Order

If your program requires a predictable sequence, use a list or another ordered data structure.

19

Frozenset

A frozenset is an immutable version of a set.

Once a frozenset is created, its elements cannot be added or removed.

Python
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.

20

Practical Real-World Examples

Example 1 — Removing Duplicate User IDs

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

Course Comparison
python_students = {"Ali", "Sara", "Ahmed", "Hina"}

sql_students = {"Sara", "Ahmed", "Usman"}

both_courses = python_students & sql_students

print(both_courses)
Possible Output
{'Sara', 'Ahmed'}

The intersection identifies students enrolled in both courses.

Example 3 — Website Permissions

Permissions
user_permissions = {
    "read",
    "write",
    "download"
}

if "delete" in user_permissions:
    print("Delete access granted.")
else:
    print("Delete access denied.")
Output
Delete access denied.

Example 4 — Finding Common Skills

Skills
developer_a = {
    "Python",
    "SQL",
    "Power BI",
    "Excel"
}

developer_b = {
    "Python",
    "SQL",
    "JavaScript"
}

common_skills = developer_a & developer_b

print(common_skills)
Output
{'Python', 'SQL'}
21

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.

22

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.

23

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.
Challenge Starter
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))
Challenge Goal

Try modifying the student names and experiment with different set operations. This challenge combines several important set concepts into one practical problem.

24

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?

25

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.
  • in and not in perform 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.
  • frozenset provides an immutable set.
Key Takeaway

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.