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 Program to Find Numbers Divisible by Another Number
Python String capitalize()
Python String strip()
Python super()
Python String rstrip()
Python String partition()
Python divmod()
Python Program to Return Multiple Values From a Function
Java Program to Implement the Binary Counting Method to Generate Subsets of a Set
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python Program to Find ASCII Value of Character
Python Program to Find the Size (Resolution) of a Image
Python complex()
Python Errors and Built-in Exceptions
Python List pop()
Python String count()
Python pass statement
Python Program to Copy a File
Python Program to Delete an Element From a Dictionary
Python Set intersection()
Python List index()
Python Set discard()
Python Namespace and Scope
Python property()
Python Inheritance
Python Dictionary setdefault()
Python sorted()
Node.js vs Python for Backend Development
Python tuple()
Python Set intersection_update()
Python Program to Print all Prime Numbers in an Interval
Python Program to Find Sum of Natural Numbers Using Recursion