Python set Method - intersection()

The intersection() method in Python is used to find the intersection of two or more sets. The method returns a new set that contains only the elements that are common to all the sets.

The syntax for the intersection() method is as follows:

intersection_set = set1.intersection(set2, set3, ...)
Source:‮i.www‬giftidea.com

Here, set1, set2, set3, etc. are the sets for which we need to find the intersection. The method returns a new set intersection_set that contains only the elements that are common to all the sets.

Example:

# Creating three sets
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
set3 = {4, 5, 6, 7}

# Finding the intersection of the sets
intersection_set = set1.intersection(set2, set3)

# Displaying the sets and the intersection
print(set1)               # Output: {1, 2, 3, 4}
print(set2)               # Output: {3, 4, 5, 6}
print(set3)               # Output: {4, 5, 6, 7}
print(intersection_set)   # Output: {4}

In the above example, the intersection() method is used to find the intersection of the sets set1, set2, and set3. The new set intersection_set contains only the elements that are common to all the sets, in this case the element 4. The original sets and the intersection set are printed to show their contents. It is important to note that the order of elements in a set is undefined and may not match the order in which they were added.