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 List index()
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python slice()
Python List append()
Python Program to Swap Two Variables
Python RegEx
Python int()
Python Program to Create a Countdown Timer
Python bytes()
Python map()
Python Program to Iterate Over Dictionaries Using for Loop
Python String center()
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python Program to Make a Flattened List from Nested List
Python Program to Convert Celsius To Fahrenheit
Python Program to Find Factorial of Number Using Recursion
Python Program to Parse a String to a Float or Int
Python Program to Differentiate Between del, remove, and pop on a List
Python Program to Print all Prime Numbers in an Interval
Python bool()
Python hex()
Python Machine Learning - Sebastian Raschka
Python List pop()
Python Program to Transpose a Matrix
Python reversed()
Python Dictionary copy()
Python Program to Convert Decimal to Binary Using Recursion
Python Program to Safely Create a Nested Directory
Python if...else Statement
Python oct()
Python String istitle()
Python @property decorator