Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python Set intersection_update() method



The Python Setintersection_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 Setintersection_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 codeif __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 theintersection_update() method on three sets −

# Define three setsset1 = {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 set3set1.intersection_update(set2, set3)# Print the updated set1print(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 setset1 = {1, 2, 3}set2 = set()# Update set1 to keep only elements present in both setsset1.intersection_update(set2)# Print the updated set1print(set1)  # Output: set()

Output

set()

Example 4

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

# Define a set and a listset1 = {1, 2, 3, 4, 5}list1 = [3, 4, 5, 6, 7]# Update set1 to keep only elements present in both set1 and list1set1.intersection_update(list1)# Print the updated set1print(set1)  # Output: {3, 4, 5}

Output

{3, 4, 5}
python_set_methods.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp