Python Set Difference

python-set-difference-ipcisco-1

How to find the differences of two sets? Or how to get the items that reside in one python set but not in the other set? In this lesson of Python, we will see this compariosn and python set difference.  We can compare two or more sets and check that if are there any common items in these sets. And the return of this method is the items that are not common. Here, we will use set difference method. Below, you can find examples for this widely used method.

 


You can also check all the other Python Set Methods


 

Let’s show this with different code examples.

 

dwarves1 = {"Thorin", "Balin", "Dwalin"}
dwarves2 = {"Gimli", "Balin", "Thorin"}
dwarves3 = dwarves1.difference(dwarves2)
print(dwarves3)

 

The only item that exist in the first set but not in the second set is “Dwalin”. So the output of this python code will be:

 

{'Dwalin'}

 


You can also check Python Set Operations


 

python-set-difference-ipcisco-1

 

Let’s do another example with a number set.

 

numbers1 = {1,2,3,4,5,6,7,300}
numbers2 = {1,2,3,100}
numbers3 = {1,2,3,4,5,200}
print(numbers1.difference(numbers2,numbers3))

 

The output of this python set difference code is given below:

 

{6, 7, 300}

 

python-set-difference-ipcisco-2

 

In this lesson, we have learned how to compare two or more sets to find the uncommon items. This is an important method used in python programming. You can increase code examples and practice more on this python method.

 

Back to: Python Programming Course > Python Sets

Leave a Reply

Your email address will not be published. Required fields are marked *

Python Programming Course

Collapse
Expand
Latest Blog Posts