intersection_update () in Python for finding common elements in n arrays



Examples:

 Input: arr = [[1,2,3,4], [8,7,3,2], [9,2,6,3], [5, 1,2,3]] Output: Common Elements = [2,3] 

We can quickly solve this problem in python with the intersection_update () Set () data structures .

How does intersection_update () work?

Suppose we have two sets A and B, then operation A.intersection_update (B) updates set A with common elements in sets A and B. For example, A = set ([1,2,3]) and B = set ([4,2,3]) now after accepting A.intersection_update (B) , the value of set A will be [2,3]. Syntax anySet.intersection_update (iterable) .

# Function for finding common elements in n arrays

def commonElements (arr):

 

# initialize the result with the first array as a set

result = set (arr [ 0 ])

 

# now iterate over the list of arrays, starting c

# second array and take intersection_update () from

# each array with the result. Each operation will

# update the result value with shared values ​​in

# result set and overlap set

for currSet in arr [ 1 :]:

  result.intersection_update (currSet)

 

return list (result)

 
# Driver code

if __ name__ = = "__ main__" :

arr = [[ 1 , 2 , 3 , 4 ], [ 8 , 7 , 3 , 2 ], [ 9 , 2 , 6 , 3 ], [ 5 , 1 , 2 , 3 ]]

output = commonElements (arr)

if len (output) & gt;  0 :

print output

else :

print `No Common Elements Found`

Output:

 Common Elements = [2,3] 

This article is courtesy of Shashank Mishra (Gullu) . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you`d like to share more information on the topic discussed above.