Following image depicts the set difference in mathematical terms.

## 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.

1 2 3 4 5 6 7 8 |
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 2 3 4 5 |
{1, 4} {2, 5} {6, 7} |

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

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

1 2 3 |
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.

1 2 3 |
print(set1.difference(set2).difference(set3)) |

Output: `{1}`

Reference: Official Documentation