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

| | | | |

👻 See our latest reviews to choose the best laptop for Machine Learning and Deep learning tasks!

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.

👻 Read also: what is the best laptop for engineering students in 2022?

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method