&
or
intersection()
0r
set1.intersection(set2)
we can provide set of list , string etc
Code:
Knowledge:
n set theory, intersection is an operation that returns
only the elements that are common between two or more sets.
It is often contrasted with the union operation,
which combines all elements from multiple sets.
The intersection focuses on finding shared elements,
making it useful when you want to identify what is present in both sets.
In Python, the intersection can be performed u
sing either the & operator or the intersection() method.
Both approaches yield the same result,
but the method is generally more explicit
and can be helpful when working with multiple sets.
Using the & Operator
The & operator finds the intersection between
two sets by returning a new set containing only the common elements. For example:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
result = set1 & set2
print(result) # Output: {3, 4}
Here, {3, 4} is the intersection because
these are the only elements present in both sets.
Using the intersection() Method
Alternatively, the intersection() method can be used to
achieve the same result. This method is often preferred for clarity:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
result = set1.intersection(set2)
print(result) # Output: {3, 4}
Multiple Set Intersections
You can also perform intersection operations with more than
two sets, either by chaining the & operator or using the intersection()
method:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
set3 = {4, 5, 6, 7}
result = set1 & set2 & set3
print(result) # Output: {4}
In this case, {4} is the only element present in all three sets.
Practical Use Cases
Intersection is commonly used in scenarios like finding common interests,
comparing datasets, or filtering data. It is a valuable tool for
identifying overlapping elements in sets, making it essential for
tasks that involve comparison or shared characteristics.
