Python Set Difference

Filed Under: Python

If there are two sets A and B, then the difference between A and B (A-B) is a new set of elements that are present in A but not in B.

Following image depicts the set difference in mathematical terms.

Set Difference

Set Difference

Python Set Difference

Python set class has difference() function that returns the difference of two or more sets as a new set.

Let’s look at some examples of python set difference() function.


set1 = {1, 2, 3, 4}
set2 = {2, 3, 5, 6}
set3 = {3, 4, 6, 7}

print(set1.difference(set2))
print(set2.difference(set3))
print(set3.difference(set1))

Output:


{1, 4}
{2, 5}
{6, 7}

The output is same as shown in the first image explaining set difference.

Python Set Difference

Python Set Difference

Let’s look at another example where we will get the difference between multiple sets.


print(set1.difference(set2, set3))

Output: {1}

Since set difference() function returns a new set, we can take the set difference by a chain of difference() function calls too.


print(set1.difference(set2).difference(set3))

Output: {1}

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages