Chapter 9: Python Sets – Creating, Adding, Removing and Using Set Operations
9.1 Introduction
In the previous chapters, we learned about Lists and Tuples.
Python also provides another useful collection type called a Set.
A set is a collection of unique elements. Unlike lists and tuples, sets do not store duplicate values.
For example:
numbers = {10, 20, 30, 20, 10} print(numbers)
Output:
{10, 20, 30}
The duplicate values were automatically removed.
Sets are particularly useful when you need to:
- Remove duplicate values
- Check membership
- Compare collections
- Find common elements
- Find differences between collections
- Perform mathematical set operations
9.2 What is a Set?
A set is an unordered collection of unique elements.
Example:
fruits = {"Apple", "Banana", "Mango"} print(fruits)
A set does not use indexes like a list.
For example, this is not valid:
fruits[0]
Sets are designed for membership testing and set operations rather than positional access.
9.3 Creating a Set
Sets are commonly created using curly braces {}.
numbers = {10, 20, 30, 40} print(numbers)
Output:
{10, 20, 30, 40}
The order in which elements appear when displayed should not be relied upon.
9.4 Duplicate Values in a Set
Sets automatically eliminate duplicate values.
numbers = {10, 20, 10, 30, 20, 40} print(numbers)
Output will contain each value only once:
{10, 20, 30, 40}
This makes sets very useful for removing duplicates.
9.5 Creating an Empty Set
There is an important difference between {} and set().
This:
data = {}
creates an empty dictionary, not a set.
To create an empty set, use:
data = set() print(data)
Output:
set()
9.6 Sets Can Contain Different Data Types
A set can contain different types of hashable values.
Example:
data = {"Aman", 20, 85.5, True} print(data)
However, using elements of a consistent type often makes programs easier to understand.
9.7 Set Elements Must Be Hashable
Set elements must be hashable.
Common hashable values include:
- Integers
- Floats
- Strings
- Booleans
- Tuples containing hashable elements
For example:
data = {(10, 20), (30, 40)} print(data)
A list cannot be directly stored inside a set:
data = {[1, 2], [3, 4]}
This raises a TypeError because lists are mutable and therefore unhashable.
9.8 Adding an Item with add()
The add() method adds one element to a set.
fruits = {"Apple", "Banana"} fruits.add("Mango") print(fruits)
The set now contains:
{'Apple', 'Banana', 'Mango'}
The exact display order may vary.
9.9 Adding an Existing Item
If you add an item that is already present, the set remains unchanged.
numbers = {10, 20, 30} numbers.add(20) print(numbers)
Output contains only one 20.
9.10 Adding Multiple Items with update()
The update() method adds elements from another iterable.
fruits = {"Apple", "Banana"} fruits.update(["Mango", "Orange"]) print(fruits)
The resulting set contains all four unique fruits.
You can also use another set:
numbers = {1, 2, 3} numbers.update({4, 5, 6}) print(numbers)
9.11 Removing an Item with remove()
The remove() method removes a specified element.
fruits = {"Apple", "Banana", "Mango"} fruits.remove("Banana") print(fruits)
If the element exists, it is removed.
If it does not exist, remove() raises a KeyError.
9.12 Removing an Item with discard()
The discard() method also removes an element.
The difference is that discard() does not raise an error if the item is absent.
fruits = {"Apple", "Banana", "Mango"} fruits.discard("Orange") print(fruits)
The program continues normally.
Important difference
| Method | If item does not exist |
|---|---|
| remove() | Raises KeyError |
| discard() | Does nothing |
9.13 Removing an Arbitrary Item with pop()
The pop() method removes and returns an arbitrary element from a set.
numbers = {10, 20, 30, 40} removed = numbers.pop() print("Removed:", removed) print("Remaining:", numbers)
Because sets are unordered, you should not assume which element will be removed.
9.14 Clearing a Set
The clear() method removes all elements.
numbers = {10, 20, 30} numbers.clear() print(numbers)
Output:
set()
9.15 Finding the Size of a Set
Use len() to find the number of elements.
fruits = {"Apple", "Banana", "Mango"} print(len(fruits))
Output:
3
Duplicate values are counted only once because a set stores unique elements.
9.16 Checking Membership
The in operator is very useful with sets.
fruits = {"Apple", "Banana", "Mango"} if "Mango" in fruits: print("Mango is available")
Output:
Mango is available
You can also use not in:
if "Orange" not in fruits: print("Orange is not available")
Sets are particularly efficient for membership testing.
9.17 Looping Through a Set
You can use a for loop to process each element.
fruits = {"Apple", "Banana", "Mango"} for fruit in fruits: print(fruit)
The order of output should not be assumed.
9.18 Sets Are Unordered
A set does not provide positional indexing.
For example:
numbers = {10, 20, 30}
You cannot reliably do:
print(numbers[0])
This results in a TypeError.
If you need positional access, use a list or tuple.
9.19 Converting a List to a Set
The set() function can convert an iterable into a set.
This is a common technique for removing duplicate values.
numbers = [10, 20, 10, 30, 20, 40] unique_numbers = set(numbers) print(unique_numbers)
The result contains only unique values.
9.20 Converting a Set to a List
You can convert a set back to a list.
numbers = {10, 20, 30} numbers_list = list(numbers) print(numbers_list)
Remember that the order should not be assumed.
If you need a predictable sorted order:
numbers_list = sorted(numbers) print(numbers_list)
9.21 Set Union
Union combines all unique elements from two sets.
Suppose:
A = {1, 2, 3} B = {3, 4, 5}
The union is:
{1, 2, 3, 4, 5}
Use the | operator:
A = {1, 2, 3} B = {3, 4, 5} result = A | B print(result)
You can also use the union() method:
result = A.union(B) print(result)
Both approaches produce the same set of unique elements.
9.22 Set Intersection
Intersection finds elements that exist in both sets.
Example:
A = {1, 2, 3, 4} B = {3, 4, 5, 6} result = A & B print(result)
Output:
{3, 4}
You can also use:
result = A.intersection(B)
9.23 Set 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} result = A - B print(result)
Output:
{1, 2}
The reverse gives:
print(B - A)
Output:
{5, 6}
Therefore:
A - B
and:
B - A
are generally different.
9.24 Symmetric Difference
Symmetric difference contains elements that belong to either set, but not both.
Example:
A = {1, 2, 3, 4} B = {3, 4, 5, 6} result = A ^ B print(result)
Output:
{1, 2, 5, 6}
The same operation can be performed using:
result = A.symmetric_difference(B)
9.25 Set Operations Summary
Suppose:
A = {1, 2, 3} B = {3, 4, 5}
| Operation | Operator | Result |
|---|---|---|
| Union | A | B | {1, 2, 3, 4, 5} |
| Intersection | A & B | {3} |
| Difference | A - B | {1, 2} |
| Difference | B - A | {4, 5} |
| Symmetric Difference | A ^ B | {1, 2, 4, 5} |
These operations are among the most important features of Python sets.
9.26 Union with union()
Example:
python_students = {"Aman", "Ravi", "Neha"} java_students = {"Ravi", "Priya", "Karan"} all_students = python_students.union(java_students) print(all_students)
The result contains every unique student.
9.27 Intersection with intersection()
Find students who are learning both subjects:
python_students = {"Aman", "Ravi", "Neha"} java_students = {"Ravi", "Priya", "Karan"} both = python_students.intersection(java_students) print(both)
Output:
{'Ravi'}
9.28 Difference with difference()
Find students learning Python but not Java:
python_students = {"Aman", "Ravi", "Neha"} java_students = {"Ravi", "Priya", "Karan"} only_python = python_students.difference(java_students) print(only_python)
Output:
{'Aman', 'Neha'}
9.29 Symmetric Difference with a Method
A = {1, 2, 3} B = {3, 4, 5} result = A.symmetric_difference(B) print(result)
Output:
{1, 2, 4, 5}
9.30 Updating a Set with Union
The update() method can add elements from another iterable to an existing set.
A = {1, 2, 3} B = {3, 4, 5} A.update(B) print(A)
The resulting set contains:
{1, 2, 3, 4, 5}
Unlike union(), update() modifies the existing set.
9.31 Intersection Update
The intersection_update() method keeps only elements that exist in both sets.
A = {1, 2, 3, 4} B = {3, 4, 5, 6} A.intersection_update(B) print(A)
Output:
{3, 4}
9.32 Difference Update
The difference_update() method removes elements found in another set.
A = {1, 2, 3, 4} B = {3, 4, 5} A.difference_update(B) print(A)
Output:
{1, 2}
9.33 Symmetric Difference Update
The symmetric_difference_update() method updates a set so that it contains elements belonging to either set, but not both.
A = {1, 2, 3} B = {3, 4, 5} A.symmetric_difference_update(B) print(A)
Output:
{1, 2, 4, 5}
9.34 Checking Subsets
A set A is a subset of B if every element of A is also present in B.
Example:
A = {1, 2} B = {1, 2, 3, 4} print(A.issubset(B))
Output:
True
You can also use:
print(A <= B)
9.35 Checking Supersets
A set A is a superset of B if it contains every element of B.
A = {1, 2, 3, 4} B = {1, 2} print(A.issuperset(B))
Output:
True
You can also use:
print(A >= B)
9.36 Checking Disjoint Sets
Two sets are disjoint when they have no elements in common.
Example:
A = {1, 2, 3} B = {4, 5, 6} print(A.isdisjoint(B))
Output:
True
If they have at least one common element:
A = {1, 2, 3} B = {3, 4, 5} print(A.isdisjoint(B))
Output:
False
9.37 Frozen Sets
Python also provides a collection called frozenset.
A frozenset is an immutable version of a set.
Example:
numbers = frozenset([1, 2, 3, 4]) print(numbers)
You cannot use methods such as add() or remove() on a frozenset.
For example:
numbers.add(5)
would raise an error.
9.38 Set Comprehension
Python supports set comprehension, similar to list comprehension.
Example:
numbers = {1, 2, 3, 4, 5} squares = {number ** 2 for number in numbers} print(squares)
Output:
{1, 4, 9, 16, 25}
A condition can also be used:
numbers = range(1, 11) even_numbers = {number for number in numbers if number % 2 == 0} print(even_numbers)
Output contains:
{2, 4, 6, 8, 10}
9.39 Removing Duplicate Values
One of the most common practical uses of sets is removing duplicates.
Example:
numbers = [10, 20, 10, 30, 20, 40, 30] unique_numbers = set(numbers) print(unique_numbers)
The result contains only unique values.
If you need a list again:
unique_numbers = list(set(numbers)) print(unique_numbers)
Remember that this approach does not guarantee preservation of the original order.
9.40 Preserving Order While Removing Duplicates
If you want to remove duplicates while preserving the first occurrence order, a useful approach is:
numbers = [10, 20, 10, 30, 20, 40] unique_numbers = list(dict.fromkeys(numbers)) print(unique_numbers)
Output:
[10, 20, 30, 40]
This works because dictionaries preserve insertion order in modern Python.
9.41 Example: Common Subjects
Suppose two students have selected different subjects.
student_a = {"Maths", "Science", "English"} student_b = {"Science", "English", "Computer"} common = student_a & student_b print("Common subjects:", common)
Output:
Common subjects: {'Science', 'English'}
9.42 Example: Unique Student Names
students = [ "Aman", "Ravi", "Aman", "Neha", "Ravi", "Priya" ] unique_students = set(students) print(unique_students)
The set contains each student name only once.
9.43 Example: Find Students in Both Courses
python = {"Aman", "Ravi", "Neha", "Priya"} web = {"Ravi", "Priya", "Karan"} both_courses = python & web print("Students in both courses:", both_courses)
Output:
Students in both courses: {'Ravi', 'Priya'}
9.44 Example: Students Only in Python
python = {"Aman", "Ravi", "Neha", "Priya"} web = {"Ravi", "Priya", "Karan"} only_python = python - web print("Only Python:", only_python)
Output:
Only Python: {'Aman', 'Neha'}
9.45 Example: Students in Either Course but Not Both
python = {"Aman", "Ravi", "Neha", "Priya"} web = {"Ravi", "Priya", "Karan"} different = python ^ web print(different)
The result contains students who belong to exactly one of the two sets.
9.46 Common Set Mistakes
Mistake 1: Creating an empty set incorrectly
Incorrect:
data = {}
This creates a dictionary.
Correct:
data = set()
Mistake 2: Trying to use indexing
Incorrect:
numbers = {10, 20, 30} print(numbers[0])
Sets do not support positional indexing.
Mistake 3: Expecting a fixed display order
Do not depend on:
numbers = {30, 10, 20} print(numbers)
being displayed in a particular order.
If order matters, use a list or sort the set when producing output.
Mistake 4: Adding a list directly to a set
This is invalid:
numbers = {1, 2, 3} numbers.add([4, 5])
A list is unhashable.
To add individual values:
numbers.update([4, 5])
9.47 List vs Tuple vs Set
| Feature | List | Tuple | Set |
|---|---|---|---|
| Ordered | Yes | Yes | No positional order |
| Mutable | Yes | No | Yes |
| Duplicates | Yes | Yes | No |
| Indexing | Yes | Yes | No |
| Slicing | Yes | Yes | No |
| Syntax | [] | () | {} |
| Main use | Changeable collection | Fixed collection | Unique values & set operations |
9.48 Mini Project: Course Enrollment Analyzer
python_students = { "Aman", "Ravi", "Neha", "Priya" } web_students = { "Ravi", "Priya", "Karan", "Rahul" } print("Python students:", python_students) print("Web students:", web_students) print("\nStudents in both courses:") print(python_students & web_students) print("\nOnly Python:") print(python_students - web_students) print("\nOnly Web:") print(web_students - python_students) print("\nStudents in either course:") print(python_students | web_students) print("\nStudents in exactly one course:") print(python_students ^ web_students)
This project demonstrates the four major set operations.
9.49 Mini Project: Duplicate Checker
numbers = input("Enter numbers separated by spaces: ").split() numbers = [int(number) for number in numbers] unique_numbers = set(numbers) print("Original list:", numbers) print("Unique values:", unique_numbers) if len(numbers) == len(unique_numbers): print("There are no duplicate values.") else: print("Duplicate values were found.")
9.50 Mini Project: Student Attendance Analyzer
all_students = { "Aman", "Ravi", "Neha", "Priya", "Karan" } present_students = { "Aman", "Neha", "Karan" } absent_students = all_students - present_students print("All students:", all_students) print("Present:", present_students) print("Absent:", absent_students)
This is a practical example of set difference.
9.51 Mini Project: Common Skills
Suppose two employees have different technical skills.
employee_a = { "Python", "HTML", "CSS", "SQL" } employee_b = { "Python", "JavaScript", "SQL", "Git" } common_skills = employee_a & employee_b print("Common skills:", common_skills)
Output contains the skills shared by both employees.
9.52 Chapter Summary
In this chapter, you learned:
- What sets are
- Creating sets
- Empty sets
- Unique elements
- Adding elements with add()
- Adding multiple elements with update()
- Removing elements with remove()
- Safely removing elements with discard()
- Removing arbitrary elements with pop()
- Clearing sets
- Finding set length
- Membership testing
- Iterating through sets
- Set union
- Set intersection
- Set difference
- Symmetric difference
- Subsets
- Supersets
- Disjoint sets
- Set comprehension
- frozenset
- Removing duplicates
- Practical set applications
The most important idea is:
A set stores unique elements and is especially useful for membership testing and mathematical set operations.
Quick Revision Questions
1. What is a set?
A set is a collection of unique elements.
2. Can a set contain duplicate values?
No.
3. How do you create an empty set?
my_set = set()
4. Which method adds one element?
add().
5. Which method adds elements from another iterable?
update().
6. What is the difference between remove() and discard()?
remove() raises KeyError if the element is absent, while discard() does nothing.
7. Which operator performs union?
|
8. Which operator performs intersection?
&
9. Which operator performs difference?
-
10. Which operator performs symmetric difference?
^
11. Can sets be indexed?
No.
12. What is a frozenset?
An immutable version of a set.
Practice Exercises
Exercise 1: Create a Set
Create a set containing five programming languages and display it.
Exercise 2: Remove Duplicates
Create a list containing duplicate numbers and use a set to find the unique values.
Exercise 3: Add Elements
Create an empty set and add five values using add().
Exercise 4: Remove Elements
Create a set of fruits and remove one fruit using discard().
Exercise 5: Union
Create two sets of numbers and find their union.
Exercise 6: Intersection
Create two sets and find the values common to both.
Exercise 7: Difference
Find the elements that are present in the first set but not the second.
Exercise 8: Symmetric Difference
Find the elements that belong to exactly one of two sets.
Exercise 9: Student Courses
Create two sets representing students enrolled in two different courses. Find students enrolled in both courses.
Exercise 10: Duplicate Checker
Take numbers from the user and determine whether duplicate values exist.
Chapter Activity
Create a Student Course Management System using Sets.
Your program should maintain sets for:
- Python students
- Web Development students
- Database students
The program should be able to display:
- Students enrolled in all three courses.
- Students enrolled in Python and Web Development.
- Students enrolled only in Python.
- All unique students.
- Students enrolled in exactly one course.
- Total number of unique students.
Use:
- Sets
- Union
- Intersection
- Difference
- Symmetric difference
- Membership operators