Applying Set Operations: Union, Intersection, and Difference in Python
Course: Python Training
Topic: Applying Set Operations: Union, Intersection, and Difference
Course Link: Python Training Course at JustAcademy
Demo Link: Register for a Course Demo
Website: JustAcademy Official Website
1. Introduction to Set Operations
Python sets are built-in data structures used to store unique elements. A set automatically removes duplicate values and is useful when working with collections where uniqueness matters. Set operations help compare two or more collections, combine their elements, and identify common or different elements.
The three fundamental set operations are:
- Union: Combines all unique elements from two sets.
- Intersection: Finds elements that are present in both sets.
- Difference: Finds elements that are present in one set but not in another.
These operations are commonly used in data analysis, database comparisons, filtering, access control, student enrollment systems, and removing duplicate records.
2. Learning Objectives
- Understand Python sets and their characteristics.
- Create sets and perform basic set operations.
- Apply union to combine unique elements.
- Apply intersection to find common elements.
- Apply difference to identify elements unique to one set.
- Understand the difference between set operators and set methods.
- Use compound operations with multiple sets.
- Apply set operations to practical programming problems.
- Avoid common mistakes when working with sets.
3. Understanding Sets in Python
A set is an unordered collection of unique, hashable elements. Sets are mutable, meaning you can add or remove elements after creation. However, individual set elements must be hashable, so lists and dictionaries cannot be stored directly inside a set.
3.1 Creating a Set
numbers = {10, 20, 30, 40}
print(numbers)
Possible output:
{40, 10, 20, 30}
The order shown in a set output may vary. Sets do not guarantee a meaningful display order.
3.2 Removing Duplicate Values
numbers = {10, 20, 10, 30, 20, 40}
print(numbers)
print(len(numbers))
Possible output:
{40, 10, 20, 30}
4
Although some values were repeated in the set literal, only unique values remain.
3.3 Creating an Empty Set
empty_set = set()
empty_dictionary = {}
print(type(empty_set))
print(type(empty_dictionary))
Output:
<class 'set'>
<class 'dict'>
Use set() to create an empty set. Empty curly braces, {}, create a dictionary instead.
4. What Are Set Operations?
Set operations compare sets mathematically. Suppose we have two sets:
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
Here, the sets contain some common elements and some elements that appear in only one set.
| Operation |
Purpose |
Result |
| Union |
Combines all unique elements from A and B. |
{1, 2, 3, 4, 5, 6, 7, 8} |
| Intersection |
Returns elements common to A and B. |
{4, 5} |
| Difference A - B |
Returns elements in A that are not in B. |
{1, 2, 3} |
| Difference B - A |
Returns elements in B that are not in A. |
{6, 7, 8} |
5. Union of Sets
The union operation combines the elements of two or more sets into a new set. Duplicate elements appear only once in the result.
In mathematical notation, the union of sets A and B is written as \(A \cup B\).
5.1 Using the Union Operator (|)
Python uses the vertical bar operator, |, to perform union between sets.
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
result = A | B
print(result)
Possible output:
{1, 2, 3, 4, 5, 6}
Explanation:
- Set A contains 1, 2, 3, and 4.
- Set B contains 3, 4, 5, and 6.
- The union includes every unique element from both sets.
- The repeated elements 3 and 4 appear only once.
5.2 Using the union() Method
The union() method performs the same operation as the | operator.
A = {"Python", "Java", "C++"}
B = {"Java", "JavaScript", "Python"}
result = A.union(B)
print(result)
Possible output:
{'Python', 'Java', 'C++', 'JavaScript'}
The exact display order can vary because sets are unordered.
5.3 Union of Multiple Sets
You can combine more than two sets in a single union operation.
A = {1, 2, 3}
B = {3, 4, 5}
C = {5, 6, 7}
result = A | B | C
print(result)
Possible output:
{1, 2, 3, 4, 5, 6, 7}
You can also use the union() method with multiple iterables:
result = A.union(B, C)
print(result)
Possible output:
{1, 2, 3, 4, 5, 6, 7}
5.4 Practical Example of Union
Imagine that two groups of students attend different programming workshops. You want to find every unique student who attends at least one workshop.
python_students = {"Aarav", "Neha", "Riya", "Karan"}
sql_students = {"Neha", "Karan", "Meera", "Rahul"}
all_students = python_students | sql_students
print(all_students)
print("Total unique students:", len(all_students))
Possible output:
{'Aarav', 'Neha', 'Riya', 'Karan', 'Meera', 'Rahul'}
Total unique students: 6
Use case: Union is useful when combining customer lists, enrolled students, available product categories, or unique website visitors from different sources.
6. Intersection of Sets
The intersection operation returns only those elements that appear in every set being compared.
In mathematical notation, the intersection of A and B is written as \(A \cap B\).
6.1 Using the Intersection Operator (&)
Python uses the ampersand operator, &, to find common elements between sets.
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
result = A & B
print(result)
Output:
{4, 5}
Explanation: The values 4 and 5 exist in both A and B, so they are included in the intersection. All other elements are excluded.
6.2 Using the intersection() Method
frontend_skills = {"HTML", "CSS", "JavaScript", "React"}
backend_skills = {"Python", "SQL", "JavaScript", "React"}
common_skills = frontend_skills.intersection(backend_skills)
print(common_skills)
Output:
{'JavaScript', 'React'}
The method returns a new set containing the elements common to the sets.
6.3 Intersection of Multiple Sets
When three or more sets are used, the intersection contains only elements shared by all of them.
A = {1, 2, 3, 4, 5}
B = {2, 3, 4, 6}
C = {3, 4, 7, 8}
result = A & B & C
print(result)
Output:
{3, 4}
6.4 Practical Example of Intersection
A company wants to identify customers who purchased products from both its online store and its physical store.
online_customers = {"Amit", "Neha", "Riya", "Karan"}
store_customers = {"Neha", "Karan", "Meera", "Amit"}
both_channels = online_customers & store_customers
print("Customers using both channels:", both_channels)
Possible output:
Customers using both channels: {'Amit', 'Neha', 'Karan'}
Use case: Intersection helps identify shared customers, common skills, mutual followers, overlapping permissions, and records present in multiple datasets.
7. Difference Between Sets
The difference operation returns elements that belong to one set but do not belong to another. Unlike union and intersection, difference is directional: changing the order of the sets may change the result.
The difference of A and B is written as \(A - B\).
7.1 Using the Difference Operator (-)
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
result = A - B
print(result)
Output:
{1, 2, 3}
Explanation:
- Start with all elements in A.
- Check which of those elements also exist in B.
- Remove the shared elements from the result.
- The remaining elements are 1, 2, and 3.
7.2 Reverse Difference
Difference is not commutative. The expression A - B is generally different from B - A.
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A - B)
print(B - A)
Output:
{1, 2, 3}
{6, 7, 8}
The first expression finds elements only in A. The second finds elements only in B.
7.3 Using the difference() Method
registered_students = {"Aarav", "Neha", "Riya", "Karan"}
attended_students = {"Neha", "Karan"}
absent_students = registered_students.difference(attended_students)
print(absent_students)
Output:
{'Aarav', 'Riya'}
7.4 Difference Across Multiple Sets
You can subtract more than one set from the first set.
A = {1, 2, 3, 4, 5, 6}
B = {2, 4}
C = {5, 6}
result = A.difference(B, C)
print(result)
Output:
{1, 3}
7.5 Practical Example of Difference
A company wants to find employees who have access to a system but have not completed mandatory security training.
system_users = {"Asha", "Rahul", "Priya", "Vikram"}
trained_users = {"Asha", "Priya"}
pending_training = system_users - trained_users
print("Training pending:", pending_training)
Possible output:
Training pending: {'Rahul', 'Vikram'}
Use case: Difference can identify absent students, products missing from a shipment, customers who have not renewed a subscription, or users who have not completed a required task.
8. Comparing Union, Intersection, and Difference
| Feature |
Union |
Intersection |
Difference |
| Operator |
| |
& |
- |
| Method |
union() |
intersection() |
difference() |
| Purpose |
Combines unique elements. |
Finds common elements. |
Finds elements in the first set but not the second. |
| Uses both sets? |
Yes |
Yes |
Yes, with direction important. |
| Order matters? |
No, A union B equals B union A. |
No, A intersection B equals B intersection A. |
Yes, generally A - B differs from B - A. |
| Example |
{1, 2} | {2, 3} |
{1, 2} & {2, 3} |
{1, 2} - {2, 3} |
| Result |
{1, 2, 3} |
{2} |
{1} |
9. Understanding Set Diagrams Conceptually
Set operations can also be understood through Venn diagrams, where each circle represents a set.
- Union: Imagine shading the entire area covered by both circles.
- Intersection: Shade only the overlapping area shared by the circles.
- Difference A - B: Shade the portion of circle A that lies outside circle B.
- Difference B - A: Shade the portion of circle B that lies outside circle A.
These concepts make it easier to understand how set operations filter and combine information.
10. Other Useful Set Operations
In addition to union, intersection, and difference, Python supports several related operations.
10.1 Symmetric Difference
Symmetric difference returns elements that belong to either set but not both. It excludes the common elements.
The operator is ^, and the corresponding method is symmetric_difference().
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
result = A ^ B
print(result)
Output:
{1, 2, 5, 6}
10.2 Checking Subsets
A set A is a subset of B when every element of A is also present in B. Use <= or issubset().
A = {1, 2}
B = {1, 2, 3, 4}
print(A <= B)
print(A.issubset(B))
Output:
True
True
10.3 Checking Supersets
A set A is a superset of B when A contains every element of B. Use >= or issuperset().
A = {1, 2, 3, 4}
B = {1, 2}
print(A >= B)
print(A.issuperset(B))
Output:
True
True
10.4 Checking 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))
Output:
True
11. Set Operators Versus Set Methods
Python offers operators and methods for performing set operations. Both forms are useful, but there is an important difference in the types of operands they accept.
| Operation |
Operator |
Method |
| Union |
A | B |
A.union(B) |
| Intersection |
A & B |
A.intersection(B) |
| Difference |
A - B |
A.difference(B) |
| Symmetric difference |
A ^ B |
A.symmetric_difference(B) |
Set operators require set operands. The corresponding methods can accept other suitable iterables, such as lists or tuples, as arguments.
A = {1, 2, 3}
numbers = [3, 4, 5]
print(A.union(numbers))
print(A.intersection(numbers))
print(A.difference(numbers))
Output:
{1, 2, 3, 4, 5}
{3}
{1, 2}
The expression A | set(numbers) is valid, whereas A | numbers raises a TypeError because numbers is a list rather than a set.
12. Non-Mutating and In-Place Set Operations
The regular union, intersection, and difference operations return new sets and leave the original sets unchanged.
A = {1, 2, 3}
B = {3, 4, 5}
result = A | B
print("A:", A)
print("Result:", result)
Output:
A: {1, 2, 3}
Result: {1, 2, 3, 4, 5}
Python also provides in-place operators that modify the original set.
| In-place operator |
Equivalent method |
Purpose |
|= |
update() |
Adds elements from other sets. |
&= |
intersection_update() |
Keeps only common elements. |
-= |
difference_update() |
Removes elements found in the other sets. |
^= |
symmetric_difference_update() |
Keeps elements present in exactly one of the sets. |
Example of an in-place operation:
A = {1, 2, 3}
B = {3, 4, 5}
A |= B
print(A)
Output:
{1, 2, 3, 4, 5}
13. Real-World Example: Course Enrollment Analysis
Suppose an academy offers Python and SQL courses. You need to identify all enrolled students, students enrolled in both courses, and students enrolled only in Python.
python_course = {
"Aarav", "Neha", "Riya", "Karan", "Meera"
}
sql_course = {
"Neha", "Karan", "Rahul", "Meera"
}
# Students enrolled in at least one course
all_students = python_course | sql_course
# Students enrolled in both courses
both_courses = python_course & sql_course
# Students enrolled only in Python
python_only = python_course - sql_course
# Students enrolled only in SQL
sql_only = sql_course - python_course
print("All students:", all_students)
print("Both courses:", both_courses)
print("Python only:", python_only)
print("SQL only:", sql_only)
Possible output:
All students: {'Aarav', 'Neha', 'Riya', 'Karan', 'Meera', 'Rahul'}
Both courses: {'Neha', 'Karan', 'Meera'}
Python only: {'Aarav', 'Riya'}
SQL only: {'Rahul'}
Learning outcome: A few set operations can answer multiple questions about overlapping groups without requiring complicated nested loops.
14. Real-World Example: Comparing Website Visitors
A marketing team can use set operations to compare visitors from two campaigns.
campaign_a = {"user1", "user2", "user3", "user4"}
campaign_b = {"user3", "user4", "user5", "user6"}
# Visitors reached by either campaign
total_reach = campaign_a.union(campaign_b)
# Visitors reached by both campaigns
overlap = campaign_a.intersection(campaign_b)
# Visitors reached only by campaign A
unique_a = campaign_a.difference(campaign_b)
print("Unique visitors:", len(total_reach))
print("Overlapping visitors:", len(overlap))
print("Campaign A only:", unique_a)
Output:
Unique visitors: 6
Overlapping visitors: 2
Campaign A only: {'user1', 'user2'}
This approach can help analyze overlapping audiences, provided each visitor is represented consistently by the same identifier.
15. Common Mistakes and How to Avoid Them
| Mistake |
Explanation |
Correct Approach |
| Expecting a specific output order |
Sets are unordered collections. |
Compare set values rather than relying on their printed order. |
| Using a list with the union operator |
The | operator requires set operands. |
Convert the list using set() or use the union() method. |
| Assuming difference is symmetric |
A - B and B - A have different meanings. |
Keep the order of sets in mind. |
| Expecting duplicates in results |
Sets store unique elements only. |
Use a list or another suitable structure if duplicates matter. |
| Confusing difference and symmetric difference |
Difference excludes elements from the second set; symmetric difference keeps elements found in either set but not both. |
Use - for directional difference and ^ for symmetric difference. |
| Trying to store mutable elements |
Lists and dictionaries are unhashable. |
Use hashable elements such as strings, numbers, or suitable tuples. |
| Accidentally changing the original set |
In-place operators modify the existing set. |
Use regular operators when you need a separate result. |
16. Best Practices for Set Operations
- Use sets when uniqueness and membership checking are important.
- Choose union when combining unique records from multiple collections.
- Choose intersection when finding shared records.
- Choose difference when identifying items missing from another collection.
- Remember that difference depends on the order of its operands.
- Use descriptive variable names to make the purpose of each set clear.
- Use regular operators when you want a new result without modifying the original set.
- Use in-place methods only when modifying the original set is intentional.
- Convert other iterables to sets when operator-based operations are needed.
- Use sorted output for readable reports when the elements are mutually orderable.
17. Practice Exercises
Exercise 1: Union of Numbers
Create two sets containing integers. Use union to combine their elements and print the number of unique values in the result.
Exercise 2: Common Interests
Create two sets representing the hobbies of two friends. Find and display their common hobbies using intersection.
Exercise 3: Students Who Were Absent
Create one set containing registered students and another containing students who attended a class. Use difference to find registered students who did not attend.
Exercise 4: Compare Shopping Lists
Create two sets representing items purchased by two customers. Find all unique items, common items, and items purchased only by the first customer.
Exercise 5: Compare Programming Skills
Create two sets of programming skills for two job candidates. Display their common skills and the skills unique to each candidate.
Exercise 6: Symmetric Difference
Given two sets of numbers, use symmetric difference to find the values that appear in exactly one of the sets.
Exercise 7: Multiple Course Enrollment
Create three sets representing students enrolled in Python, SQL, and Power BI. Find students enrolled in all three courses using intersection.
18. Practice Exercise Solutions
Solution 1: Union of Numbers
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
combined = A | B
print(combined)
print("Unique values:", len(combined))
Possible output:
{1, 2, 3, 4, 5, 6}
Unique values: 6
Solution 2: Common Interests
friend_one = {"Reading", "Music", "Travel"}
friend_two = {"Music", "Gaming", "Travel"}
common_hobbies = friend_one & friend_two
print(common_hobbies)
Possible output:
{'Music', 'Travel'}
Solution 3: Students Who Were Absent
registered = {"Aarav", "Neha", "Riya", "Karan"}
attended = {"Aarav", "Riya"}
absent = registered - attended
print(absent)
Possible output:
{'Neha', 'Karan'}
Solution 4: Compare Shopping Lists
customer_one = {"Milk", "Bread", "Eggs"}
customer_two = {"Bread", "Rice", "Eggs"}
print("All items:", customer_one | customer_two)
print("Common items:", customer_one & customer_two)
print("Only customer one:", customer_one - customer_two)
Possible output:
All items: {'Milk', 'Bread', 'Eggs', 'Rice'}
Common items: {'Bread', 'Eggs'}
Only customer one: {'Milk'}
19. Interview Questions and Answers
Q1. What is a set in Python?
A set is a mutable collection of unique, hashable elements. It is useful for removing duplicates and performing mathematical set operations.
Q2. What is union in Python?
Union combines all unique elements from two or more sets. It can be performed using the | operator or the union() method.
Q3. What is intersection?
Intersection returns the elements common to all sets being compared. It uses the & operator or the intersection() method.
Q4. What is set difference?
Difference returns the elements that belong to the first set but not to the second set. It uses the - operator or the difference() method.
Q5. Is difference commutative?
No. In general, A - B is different from B - A because each expression starts with a different set.
Q6. Are union and intersection commutative?
Yes. Union and intersection produce equivalent results regardless of the order of their operands.
Q7. What is symmetric difference?
Symmetric difference returns elements present in either set but not in both. It uses the ^ operator or symmetric_difference().
Q8. Do set operations modify the original sets?
Regular operations such as A | B and A & B return new sets. In-place operators such as |= and &= modify the original set.
Q9. Can set operations be performed on lists?
Set operators require set operands. You can convert lists into sets or use methods such as union() and intersection() with suitable iterable arguments.
Q10. How can you find unique elements from two lists?
Convert each list to a set and apply union, for example, set(list_one) | set(list_two).
Q11. How do you find elements present in one set but not another?
Use difference, such as A - B, to find elements that occur in A but not in B.
Q12. What is a disjoint set?
Two sets are disjoint when they have no common elements. The isdisjoint() method checks this condition.
20. Quick Revision Checklist
- Sets contain unique, hashable elements.
- Use
set() to create an empty set.
- Use
| or union() to combine sets.
- Use
& or intersection() to find common elements.
- Use
- or difference() to find elements in the first set but not the second.
- Use
^ or symmetric_difference() to find elements in exactly one set.
- Union and intersection are commutative; difference generally is not.
- Regular set operations return new sets.
- In-place operations modify the original set.
- Set output order should not be relied upon.
21. Conclusion
Union, intersection, and difference are essential operations for working with sets in Python. Union combines unique elements, intersection identifies shared elements, and difference isolates elements that belong to one set but not another. These operations simplify many everyday programming tasks, including removing duplicates, comparing student records, analyzing customer groups, and identifying missing information.
Practice these operations with different datasets and learn when to use operators, methods, and in-place updates. A strong understanding of sets will help you write cleaner and more efficient Python programs.
Continue learning with JustAcademy: