Join Regular Classroom : Visit ClassroomTech

Python Set – difference() Method

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

Syntax:
set1.difference(set2)
or
set1-(set2)

Also Read: Python Set – intersection_update() Method

Example 1:

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

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

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

Output:

{'window'}

Explanation:
Here, it returned a 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() method in set
# www.codewindow.in

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

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

#diffrerence of s1 and s
print(s1-(s))

Output:

{10}
{8, 9, 7}

Explanation:
Here, first it returned a set which has all the common elements removed from the first set (s) and set s1.
Second, it returned a set which has all the common element removed from the first set (s1) and set s.


Follow Us

You Missed

Also Checkout