Python Set Difference

Summary: in this tutorial, you’ll learn about the Python Set difference and how to use it to find the difference between two or more sets.

Introduction to the Python Set difference #

The difference between the two sets results in a new set that has elements from the first set which aren’t present in the second set.

Suppose you have the following s1 and s2 sets:

s1 = {'Python', 'Java', 'C++'}
s2 = {'C#', 'Java', 'C++'}Code language: JavaScript (javascript)

The difference between s1 and s2 sets results in the following set with one element:

{'Python'}
Code language: JavaScript (javascript)

…because there is only 'Python' element from the first set that doesn’t exist in the second set.

The set difference isn’t commutative. The difference between the s2 and s1 sets returns the following set:

{'C#'}Code language: JavaScript (javascript)

The following Venn diagram illustrates the difference between the s1 and s2 sets: