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 range()
Python Program to Differentiate Between type() and isinstance()
Python abs()
Python Program to Sort a Dictionary by Value
Python strftime()
Python sleep()
Python Set issubset()
Python compile()
Python pow()
Python Machine Learning - Sebastian Raschka
Python Program to Multiply Two Matrices
Python String join()
Python Program to Display Powers of 2 Using Anonymous Function
Python String maketrans()
Python divmod()
Python String isprintable()
Python type()
Python Program to Check if a Key is Already Present in a Dictionary
Python Program to Convert Celsius To Fahrenheit
Python Program to Check Whether a String is Palindrome or Not
Python List clear()
Python Set intersection_update()
Python Dictionary
Python List remove()
Python Program to Safely Create a Nested Directory
Python Program to Check Armstrong Number
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python String title()
Python Program to Check the File Size
Python Program to Split a List Into Evenly Sized Chunks
Python bin()
Python Dictionary update()