Tutorial Study Image

Python intersection()

The intersection() function in python helps to find the common elements in the sets. This function returns a new set that contains the elements that common in all comparison sets.


A.intersection(*other_sets) #where A is a set of any iterables, like strings, lists, and dictionaries.
 

intersection() Parameters:

The intersection() function can take many set parameters for the comparison(* indicates) and separate the sets with commas. We can also find the intersection of sets using & operator(intersection operator).

Parameter Description Required / Optional
A The set to search for equal items in Required
other_sets The other set to search for equal items. Optional

intersection() Return Value

The return value is always a set. If no parameters are passed, it returns a shallow copy of the set.

Input Return Value
sets a set with common elements

Examples of intersection() method in Python

Example 1: How intersection() works in Python?


A = {'a', 'b', 'c', 'd'}
B = {'c', 'e', 'f', 'a'}
C = {'d', 'f', 'a', 'g'}

print(A.intersection(B))
print(B.intersection(C))
print(A.intersection(C))
print(C.intersection(A, B))
 

Output:


{'a', 'c'}
{'f', 'a'}
{'a', 'd'}
{'a'}

Example 2: How set Intersection works using & operator?


A = {'a', 'b', 'c', 'd'}
B = {'c', 'e', 'f', 'a'}
C = {'d', 'f', 'h', 'g'}

print(A & B)
print(B & C)
print(A & C)
print(A & B & C)
 

Output:


{'a', 'c'}
{'f'}
{'d'}
{}