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 ascii()
Python String isidentifier()
Python pow()
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python List Comprehension
Python List index()
Python isinstance()
Python Set symmetric_difference()
Python Program to Get a Substring of a String
Python Program to Shuffle Deck of Cards
Python next()
Python String rstrip()
Python memoryview()
Python bin()
Python Sets
Python Program to Parse a String to a Float or Int
Python Iterators
Python Set remove()
Python String isnumeric()
Python Program to Randomly Select an Element From the List
Python String casefold()
JavaScript Map and Set
Python Program to Convert Two Lists Into a Dictionary
Deep Learning in Python - LazyProgrammer
Python list()
Python Program to Slice Lists
Python String isalnum()
Python Set issubset()
Python Program to Check the File Size
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python List
Intelligent Projects Using Python - Santanu Pattanayak