Python Set Difference


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)


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:






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}


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


{6, 7, 300}




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 *


IPCisco is the Winner! “Best Certification Study Journey of 2019!”