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

Python Set intersection_update() method



The Python Set intersection_update() method is used to update a set with the intersection of itself and one or more other sets. This means it modifies the original set to contain only elements that are present in all the sets involved.

It performs an in-place intersection operation which is more efficient than creating a new set. This method is useful for filtering a set based on the common elements it shares with other sets.

Syntax

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

set.intersection_update(*others)

Parameters

This function accepts variable number of set objects as parameters.

Return value

This method returns the updated set with elements common to all specified sets.

Example 1

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

def commonEle(arr):

# initialize res with set(arr[0])
    res = set(arr[0])

# new value will get updated each time function is executed
    for curr in arr[1:]: # slicing
       res.intersection_update(curr)
    return list(res)

# Driver code
if __name__ == "__main__":
   nest_list=[['t','u','o','r','i','a','l'], ['p','o','i','n','t'], ['t','u','o','r','i','a','l'],       ['p','y','t','h','o','n']]
   out = commonEle(nest_list)
if len(out) > 0:
   print (out)
else:
   print ('No Common Elements')

Output

['o', 't']

Example 2

As we can perform intersection on two sets and update result in the first set, in the same way we can perform on multiple sets also. This example is about applying the intersection_update() method on three sets −

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

# Update set1 to keep only elements present in set2 and set3
set1.intersection_update(set2, set3)

# Print the updated set1
print(set1)  # Output: {4, 5}

Output

{4, 5}

Example 3

In this example we are performing the intersection on a non-empty set and an empty set which results in an empty set −

# Define a non-empty set and an empty set
set1 = {1, 2, 3}
set2 = set()

# Update set1 to keep only elements present in both sets
set1.intersection_update(set2)

# Print the updated set1
print(set1)  # Output: set()

Output

set()

Example 4

Now, in this example we are applying the intersect_update() method on a set and a list, which gives the result as a set −

# Define a set and a list
set1 = {1, 2, 3, 4, 5}
list1 = [3, 4, 5, 6, 7]

# Update set1 to keep only elements present in both set1 and list1
set1.intersection_update(list1)

# Print the updated set1
print(set1)  # Output: {3, 4, 5}

Output

{3, 4, 5}
python_set_methods.htm
Advertisements