Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python Set intersection() method



The Python Set intersection() method is used to find the common elements between two or more sets. It returns a new set containing only the elements that are present in all the sets that are being compared. This function can be called on a set and passed one or more sets as arguments.

Alternatively the & operator can be used to achieve the same result.

Syntax

Following is the syntax and parameters of Python Set intersection() method −

set1.intersection(*others)

Parameter

This function accepts variable number of set objects as parameters.

Return value

This method returns new set containing elements common to all specified sets.

Example 1

Following is the example to perform a search operation which is made to find the common elements by interpreter implicitly and is returned back as a set to the respective reference −

set_1 = {'t','u','t','o','r','i','a','l'}
set_2 = {'p','o','i','n','t'}
set_3 = {'t','u','t'}
#intersection of two sets
print("set1 intersection set2 : ", set_1.intersection(set_2))
# intersection of three sets
print("set1 intersection set2 intersection set3 :", set_1.intersection(set_2,set_3))

Output

set1 intersection set2 :  {'o', 'i', 't'}
set1 intersection set2 intersection set3 : {'t'}

Example 2

In this example we use the lambda expression to create an inline function for selection of elements with the help of filter function checking that element is contained in both the list or not −

def interSection(arr1,arr2): # finding common elements

    # using filter method to find identical values via lambda function
    values = list(filter(lambda x: x in arr1, arr2))
    print ("Intersection of arr1 & arr2 is: ",values)

# Driver program
if __name__ == "__main__":
   arr1 = ['t','u','t','o','r','i','a','l']
   arr2 = ['p','o','i','n','t']
   interSection(arr1,arr2)

Output

Intersection of arr1 & arr2 is:  ['o', 'i', 't']

Example 3

Here in this example the & operator is used to find the intersection of sets −

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

# Find the intersection using the & operator
intersection_set = set1 & set2

# Print the result
print(intersection_set)  # Output: {3, 4, 5}

Output

{3, 4, 5}

Example 4

When we perform the intersection between non-empty set and an empty set then the result will be an empty set. Here in this example we performed intersection using intersection() method −

set1 = {1, 2, 3}
set2 = set()

# Find the intersection
intersection_set = set1.intersection(set2)

# Print the result
print(intersection_set)  # Output: set()

Output

set()
python_set_methods.htm
Advertisements