Home » Python

Python Set difference() Method with Example

Python Set difference() Method: Here, we are going to learn how to get the set with the different elements that does not exist in the second set?
Submitted by IncludeHelp, on November 27, 2019

Set difference() Method

difference() method is used to find the difference of 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:

    set_name1.difference(set_name2)

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:

# Python Set difference() Method with Example

# 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:

# Python Set difference() Method with Example

# 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'}






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.