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 issubclass()
Python float()
Python Program to Merge Mails
Python Program to Generate a Random Number
Python Program to Count the Number of Digits Present In a Number
Python File I/O Operation
Python map()
Python Program to Trim Whitespace From a String
Python List remove()
Python list()
Python time Module
Python Set add()
Python Program Read a File Line by Line Into a List
Python format()
Python Program to Find All File with .txt Extension Present Inside a Directory
Python Dictionary update()
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python iter()
Python Program to Multiply Two Matrices
Python hash()
Python Objects and Classes
Python Program to Check if a Number is Odd or Even
Python Program to Measure the Elapsed Time in Python
Python Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
Python Data Structures and Algorithms - Benjamin Baka
Python Program to Count the Number of Each Vowel
Python Statement, Indentation and Comments
Python Program to Solve Quadratic Equation
Python Function Arguments
Python bytes()
Python frozenset()
Python frozenset()