Home »
Python
Python Set difference() Method (with Examples)
Python Set difference() Method: In this tutorial, we will learn about the difference() method of the set class with its usage, syntax, parameters, return type, and examples.
By IncludeHelp Last updated : June 14, 2023
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'}