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 Operators
Python filter()
Python time Module
Python Data Structures and Algorithms - Benjamin Baka
Python Program to Find the Largest Among Three Numbers
Python Decorators
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python Machine Learning Cookbook - Practical solutions from preprocessing to Deep Learning - Chris A...
Python Anonymous / Lambda Function
Python Program to Get a Substring of a String
Python Namespace and Scope
Python String rstrip()
Converting Between an Array and a Set in Java
Python complex()
Intelligent Projects Using Python - Santanu Pattanayak
Python List reverse()
Python exec()
Python Program to Convert Kilometers to Miles
Python Program to Compute all the Permutation of the String
Python Global Keyword
Python Machine Learning Eqution Reference - Sebastian Raschka
Python Dictionary pop()
Python Dictionary keys()
Python Program to Sort a Dictionary by Value
Python Program to Append to a File
Python Program to Extract Extension From the File Name
Python String isupper()
Python Program to Make a Simple Calculator
Python String startswith()
Python int()
Python bool()
Python Dictionary popitem()