Python Set Difference Method Explained
In this Python tutorial, we’ll learn how to easily use Python set difference method. Multiple examples will be used for detailed demonstration of the role of difference method in Python set.
Introduction: Python Set Difference Method
This method is used to return a set which consist of items that are present in first Python set and not present in the second set. Don’t worry we’ll understand it practically with proper examples.
Get Zeeshan Ali’s stories in your inbox
Join Medium for free to get updates from this writer.
Let’s first understand its syntax. Then we’ll implement it using practical Python code examples.
Syntax of Difference Method
setA.difference(setB)- We’ve two Python sets. Set A and set B.
- The difference method takes a single argument. A set will be passed to it. The resulting set will not include items that are present in that set (e.g. set B in this case).
- This method returns a set which include items of set A that are not present in set B.
Implementing Python Set Difference Method (Detailed Examples)
Below examples will implement the difference method in different type of programs for better understanding.
Example 1: Find Difference Between Two Sets
a={1,2,4,5}
b={2,6,5,0,4,7}
res=a.difference(b)
print(res)Output
{1}- We’ve created 2 Python sets.
- After that, we’ve applied difference method on it. In this case, set A is the original set and set B is the specified set.
- Difference method will return a set of items that are present in set A but not present in set B.
- As a result, 1 is returned which means 1 is not present in the specified set (B).
Let’s now make the set B original and set A a specified set. See below:
res=b.difference(a)
print(res)Output
{0, 6, 7}In this case, the difference method will return a set of items that are present in set B but not present in set A.
Example 2: Empty Set Returned By Difference Method
Let’s see what is returned if no unique items are found in first set. See below: Continue reading…




