Home » Python

Python Set difference_update() Method with Example

Python Set difference_update() Method: Here, we are going to learn how to remove the unwanted elements from the set and update the set in Python?
Submitted by IncludeHelp, on November 27, 2019

Set difference_update() Method

difference_update() method is used to update the set with the elements of this (original) set (set1) by removing the elements from another set (set2) that do not exist in the set1 and repeated elements.

Syntax:

    set_name1.difference_update(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 'NoneType'>, it returns nothing.

Example 1:

# Python Set difference_update() Method with Example

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

# printing the sets before difference_update() call
print("cars_1:", cars_1)
print("cars_2:", cars_2)

# difference_update() method call
cars_1.difference_update(cars_2)

# printing the sets after difference_update() call
print("cars_1:", cars_1)
print("cars_2:", cars_2)

Output

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

See the output, cars_1 is updated with the unique elements by removing other elements that exist in cars_2 and repeated element "Porsche".

Example 2:

# Python Set difference_update() Method with Example

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

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

# printing the differences
x.difference_update(y)
y.difference_update(z)
z.difference_update(x)

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

Output

Before difference_update()...
x: {'ABC', 'XYZ', 'PQR'}
y: {'ABC', 'XYZ', 'PQR'}
z: {'MNO', 'XYZ', 'DEF'}
After difference_update()...
x: set()
y: {'ABC', 'PQR'}
z: {'MNO', 'XYZ', '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.