In this section, we will learn what the Set difference() method is and how to use it in Python.
What is Set difference() Method in Python?
The Python Set difference() method is used to remove those elements from the Set object (the one that invoked the method) that also exist in a reference Set that we put as the argument of this method.
Note: there’s another method called difference_update() that does the same task. The difference between the two methods is that the difference() method returns a new Set object as a result (So the original Set won’t change) but the difference_update() will change the original Set object (the one that invoked this method).
Python Set difference() Method Syntax:
set.difference(anotherSetObject)
Set difference() Method Parameter:
The method takes one argument and that is a reference to a Set object.
Set difference() method Return Value
The return value of this method is a new Set object that contains only those elements of the original Set that were not in the reference Set object as well!
Example: using python set difference() method
set1 = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15} set2 = {1,2,3,4,5} result = set1.difference(set2) print(result)
Output:
{6, 7, 8, 9, 10, 11, 12, 13, 14, 15}