×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Python Set difference() Method (with Examples)

Last Updated : December 11, 2025

Python Set difference() Method

The difference() is an inbuilt method of the set class that is used to find the difference between two sets, the method is called with this set (set1), and another set (set2) is passed as an argument and it returns the set of elements that do not exist in set2.

Syntax

The following is the syntax of difference() method:

set_name1.difference(set_name2)

Parameter(s):

The following are the parameter(s):

  • set_name2 – Name of the another/second set to find the difference with set_name1.

Return Value

The return type of this method is <class 'set'>, it returns the set of elements that does not exist in set_name1.

Example 1: Use of Set difference() Method

# declaring the sets
cars_1 = {"Porsche", "Audi", "Lexus"}
cars_2 = {"Porsche", "Mazda", "Lincoln"}

# difference() method call
x = cars_1.difference(cars_2)

# printing the sets
print("cars_1:", cars_1)
print("cars_2:", cars_2)
print("x:", x)

Output

cars_1: {'Porsche', 'Lexus', 'Audi'}
cars_2: {'Porsche', 'Mazda', 'Lincoln'}
x: {'Lexus', 'Audi'}

Example 2: Use of Set difference() Method

# declaring the sets
x = {"ABC", "PQR", "XYZ"}
y = {"ABC", "PQR", "XYZ"}
z = {"DEF", "MNO", "XYZ"}

# printing the results
print("x:", x)
print("y:", y)
print("z:", z)

# printing the differences
print("x.difference(y): ", x.difference(y))
print("y.difference(x): ", y.difference(x))
print("x.difference(z): ", x.difference(z))
print("y.difference(z): ", y.difference(z))
print("z.difference(x): ", z.difference(x))

Output

x: {'XYZ', 'PQR', 'ABC'}
y: {'XYZ', 'PQR', 'ABC'}
z: {'XYZ', 'MNO', 'DEF'}
x.difference(y):  set()
y.difference(x):  set()
x.difference(z):  {'ABC', 'PQR'}
y.difference(z):  {'ABC', 'PQR'}
z.difference(x):  {'MNO', 'DEF'}
Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.