Table of Contents
1. Overview
The difference() method returns the set difference of two sets.
If A and B are two sets. The set difference of A and B is a set of elements that exists only in set A but not in B. For example:
If A = {1, 2, 3, 4} B = {2, 3, 9} Then, A - B = {1, 4} B - A = {9}

The syntax of the set difference()
method in Python is:
A.difference(B)
Here, A and B are two sets. The following syntax is equivalent to A-B
.
2. Return Value from difference()
difference()
returns the difference between two sets which is also a set. It doesn’t modify the original sets.
3. Example 1: How difference() works in Python?
A = {'a', 'b', 'c', 'd'} B = {'c', 'f', 'g'} # Equivalent to A-B print(A.difference(B)) # Equivalent to B-A print(B.difference(A))
Output
{'b', 'a', 'd'} {'g', 'f'}
You can also find the set difference using -
operator in Python.
4. Example 2: Set Difference Using – Operator.
A = {'a', 'b', 'c', 'd'} B = {'c', 'f', 'g'} print(A-B) print(B-A)
Output
{'b', 'd', 'a'} {'f', 'g'}
Related posts:
Python hasattr()
Python while Loop
Python Program to Check the File Size
Python Program Read a File Line by Line Into a List
Python String upper()
Python Set copy()
Converting Between an Array and a Set in Java
Python String maketrans()
Python Set discard()
Python Tuple
Python List copy()
Python Program to Find the Factorial of a Number
Python isinstance()
Python callable()
Python Program to Check If Two Strings are Anagram
Python Program to Return Multiple Values From a Function
Python Program to Slice Lists
Python Program to Find the Factors of a Number
Python staticmethod()
Python Program to Calculate the Area of a Triangle
Python Program to Find All File with .txt Extension Present Inside a Directory
Python Dictionary keys()
Python Program to Create a Countdown Timer
Python Program to Find Numbers Divisible by Another Number
Python Operator Overloading
Python String isspace()
Python String center()
Python String zfill()
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python Matrices and NumPy Arrays
Python Program to Split a List Into Evenly Sized Chunks
Python Modules