Python Set – intersection() Method

It is a method in python that returns the common elements between the two sets. Returns the all the common elements of the main set along the elements of the set(s) given in the argument. It doesn’t modifies the given set. It can take multiple parameters in the argument.

Syntax:
set1.intersection(set2,set3,…)
or
set1 & (set2,set3,…)

Also Read: Python Set – union() Method

Example 1:

# Python code to understand intersection() method in set
# www.codewindow.in

s1 = {2, 5, 8, 7, 9}
s = {10, 5, 2}

#intersection of s and s1
print(s.intersection(s1))

#intersection of s1 and s
print(s1 & (s))

Output:

{2, 5}
{2, 5}

Explanation:
Here, it returned all the common elements of the main set along with the elements of the specified set.

Example 2:

# Python code to understand intersection() method in set
# www.codewindow.in

s1 = {"code", "window"}
s = {"code", "website"}
s2 = {"tech", "code"}

#union of s and s1?
print(s1.intersection(s,s2))

Output:

{'code'}

Explanation:
Here, it returned all the element of the main set along with the elements of the specified set (s) and set (s2) which is “code”.


Follow Us

You Missed

Also Checkout