⊗pyPmStCSE 120 of 208 menu

Common Elements of Multiple Sets in Python

To find the intersection of several sets, i.e. the elements common to them, you need to apply the intersection method. We pass the set with which we need to find out the common elements to its parameter. The method returns the set of common elements.

Let us have two sets:

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

Let's deduce the elements they have in common:

res = st1.intersection(st2) print(res) # {'c', 'a'}

There is also a short form of this method. Let's rewrite the previous example according to it:

res = st1 & st2 print(res) # {'c', 'a'}

Two sets are given:

st1 = {'12', '6', '2'} st2 = {'6', '10', '3', '2'}

Get their common elements.

Three sets are given:

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

Obtain the set of common elements of these three sets:

{1, 2}
azbydeenesfrkakkptruuz