Set intersection() Method in Python

Python Set intersection() Method

The intersection() method is used to find the common elements that are present in two or more sets. It returns a new set containing the elements that are present in all the specified sets.

Syntax of the intersection() method:

result_set = set1.intersection(set2, set3, ...)

Parameters:

  • set1, set2, set3, ...: The sets you want to find the common elements from.

Note that you can provide multiple sets as arguments to the intersection() method to find the common elements among all the specified sets.

Example:

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

# Finding the common elements between set1 and set2
result_set = set1.intersection(set2)

print(result_set)  # Output: {4, 5} (elements that are present in both set1 and set2)

In this example, the intersection() method is applied to set1, and it takes set2 as an argument. The result is a new set containing elements that are present in both set1 (4, 5) and set2 (4, 5).

You can also provide multiple sets to the intersection() method:

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

# Finding the common elements among set1, set2, and set3
result_set = set1.intersection(set2, set3)

print(result_set)  # Output: {4} (element that is present in all three sets)

In this case, the intersection() method is used with both set2 and set3 as arguments, and the result is a set containing the element that is present in all three sets (4).