Python Set Difference

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.

Output:

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.

Output: {1}

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

Output: {1}

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

Reference: Official Documentation

By admin

Leave a Reply