⊗pyPmStSD 122 of 208 menu

Set Difference in Python

To find the elements by which the first set differs from the second, you need to use the difference method. In its parameter, we specify the set with which we want to compare the original.

Let us have two sets:

st1 = {'a', 'b', 'c', 'e'} st2 = {'b', 'w', 'c', 'a'}

Let's derive the elements by which the first set differs from the second:

res = st1.difference(st2) print(res) # {'e', 'd'}

Now let's find the elements by which the second set differs from the first:

res = st2.difference(st1) print(res) # {'w', 'c'}

In a shorter form, this method can be rewritten as follows:

res = st2 - st1 print(res) # {'w', 'c'}

Two sets are given:

st1 = {'1', '3', '5'} st2 = {'6', '8', '1', '3'}

Get the elements that are in the second set but not in the first.

Two sets are given:

st1 = {'a', 'b', 'c', 'd', 'e'} st2 = {'d', 'e', 'f', 'g', 'h'}

Get the elements that are in the first set but not in the second.

Three sets are given:

st1 = {1, 2, 4, 5} st2 = {1, 2, 3, 6} st3 = {1, 2}

Get the set of elements that are in the first and second sets, but not in the third:

{3, 4, 5, 6}

Three sets are given:

st1 = {1, 3, 6, 8} st2 = {5, 8, 10, 2} st3 = {12, 7, 3, 1}

Find the elements by which the first set differs from the second. Write down their variable st4. Find common elements for st4 and st3.

byenru