Join Regular Classroom : Visit ClassroomTech

Python Set – difference_update() Method

It is a method in python that the main set containing the elements that are there in the first set but not in the second set. It modifies the given set.

Syntax:
set1.difference_update(set2)

Also Read: Python Set – difference() Method

Example 1:

# Python code to understand difference_update() method in set
# www.codewindow.in

s1 = {"code", "window"}
s = {"code", "website"}

#difference of s and s1?
s1.difference_update(s)
print(s1)

Output:

{'window'}

Explanation:
Here, it modified the own set with all the common elements removed from the first set s1 and set s. “code” is present in both the set, so it removed that element from set s1 and returned a new set containing only window.

Example 2:

# Python code to understand difference_update() method in set
# www.codewindow.in

s1 = {2, 5, 8, 7, 9}
s = {10, 5, 2}

#difference of s and s1
s.difference_update(s1)
print(s)

Output:

{10}

Explanation:
Here, it modified the main set which has all the common elements removed (5,2) from the first set (s) and set s1.


Follow Us

You Missed

Also Checkout