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 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. And return with the items that are not common. Here, we will use set difference method.

 

Let’s show this with different 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'}

 

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. You can increase code exmaples and practice more on this python difference method.

Back to: Python Programming Course > Python Sets

Leave a Reply

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

Contact

  • info@ipcisco.com
IPCisco is the Winner! “Best Certification Study Journey of 2019!”

Cisco-ITBlogAwards-2019-Winner-IPCisco-k