Python Set difference_update() Method (with Examples)

Python Set difference_update() Method: In this tutorial, we will learn about the difference_update() method of the set class with its usage, syntax, parameters, return type, and examples. By IncludeHelp Last updated : June 14, 2023

Python Set difference_update() Method

The difference_update() is an inbuilt method of the set class that 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

The following is the syntax of difference_update() method:

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

Example 1: Use of Set difference_update() Method

# 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: Use of Set difference_update() Method

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

Load comments ↻





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