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 Set symmetric_difference()
Python String title()
Python Objects and Classes
Python break and continue
Deep Learning with Python - Francois Chollet
Python frozenset()
Python Program to Represent enum
Python String isalpha()
Python Program to Compute the Power of a Number
Python Program to Find the Square Root
Python Program Read a File Line by Line Into a List
Python String zfill()
Python List copy()
Python String join()
Python @property decorator
Python Machine Learning Eqution Reference - Sebastian Raschka
Python Set pop()
Python String format_map()
Python strftime()
Intelligent Projects Using Python - Santanu Pattanayak
Python String rsplit()
Python range()
Python Set intersection_update()
Python String istitle()
Python String isidentifier()
Python Errors and Built-in Exceptions
Python Program to Display Calendar
Python Program to Parse a String to a Float or Int
Python Program to Access Index of a List Using for Loop
Python Set symmetric_difference_update()
Python Program to Display the multiplication Table
Python Program to Check if a Number is Odd or Even