search

What is the use of the "intersection" function in Python?

In Python, the intersection() function is used to perform the intersection operation on sets. The intersection of two or more sets is a new set that contains only the elements that are common to all the participating sets. The intersection() function can take one or more sets as arguments and returns a new set that is the intersection of all the sets. Here's an example:

set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {3, 4, 5}

intersection_set = set1.intersection(set2, set3)
print(intersection_set)  # Output: {3}

In this example, the intersection() function is used to compute the intersection of set1, set2, and set3. The resulting set intersection_set contains only the element 3, which is common to all three sets.

The intersection() function can also be invoked using the ampersand operator (&) as a shorthand notation:

set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {3, 4, 5}

intersection_set = set1 & set2 & set3
print(intersection_set)  # Output: {3}

Both approaches produce the same result: a new set that contains only the elements that are present in all the participating sets.

The intersection() function is useful when you need to find the common elements among multiple sets. It can be handy for set operations such as finding shared values, performing set comparisons, or filtering data based on common attributes.

Related Questions You Might Be Interested