⊗pyPmStDSE 121 of 208 menu

Different Elements of Multiple Sets in Python

In addition to common elements, you can also find those elements by which the sets differ from each other. To do this, use the symmetric_difference method. In its parameter, we specify the set with which we want to compare the original. The method returns a new set.

Let us have two sets:

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

Let's output the elements that don't match them:

res = st1.symmetric_difference(st2) print(res) # {'b', 'x', 'w'}

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

res = st1 ^ st2 print(res) # {'b', 'x', 'w'}

Two sets are given:

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

Get the elements that are not common to these sets.

Three sets are given:

st1 = {2, 4, 8, 10} st2 = {1, 8, 3, 2} st3 = {4, 7, 3, 1}

Find the elements that are different for the first and second sets. Store them in the variable st4. Then get an array of non-matching elements st3 and st4.

byenru