The Python intersection() method is used to get similar (common) elements between two or more sets. This method actually returns a new set with an element that is common to all sets.
set.intersection(set1, set2 ... etc)
Python set intersection example
A simple example code computes the intersection between set1 and set2.
fib = {1, 1, 2, 3, 5, 8}
prime = {2, 3, 5, 7, 11}
res = fib.intersection(prime)
print(res)
Output:
Another Example using & an operator
You can use & operator to find the intersection of sets.
fib = {1, 1, 2, 3, 5, 8}
prime = {2, 3, 5, 7, 11}
print(fib ^ prime)
Output:
{1, 7, 8, 11}
For example using 3 sets
Compare 3 sets, and return a set with elements that is present in all 3 sets:
result = x.intersection(y, z)
OR
set1 = {2, 4, 5, 6}
set2 = {4, 6, 7, 8}
set3 = {1, 0, 12}
print(set1 & set2 & set3)
Output: set()
Do comment if you have any doubts or suggestions on this Pytho set method.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.