Friday, July 5, 2024
HomeLanguagesPythonintersection_update() in Python to find common elements in n arrays

intersection_update() in Python to find common elements in n arrays

We are given list of n number of arrays, find all common elements in given 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 solve this problem quickly in python using intersection_update() method of Set() data structure. How intersection_update() works ?

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

Implementation:

Python3




# Function to find common elements in n arrays
def commonElements(arr):
     
    # initialize result with first array as a set
    result = set(arr[0])
 
    # now iterate through list of arrays starting from
    # second array and take intersection_update() of
    # each array with result. Every operation will
    # update value of result with common values in
    # result set and intersected 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) > 0:
        print ("Common Element = ",output)
    else:
        print ('No Common Elements Found')


Output

Common Element =  [2, 3]

This article is contributed by Shashank Mishra (Gullu). If you like Lazyroar and would like to contribute, you can also write an article using write.neveropen.co.za or mail your article to review-team@neveropen.co.za. See your article appearing on the Lazyroar main page and help other Geeks.

Calisto Chipfumbu
Calisto Chipfumbuhttp://cchipfumbu@gmail.com
I have 5 years' worth of experience in the IT industry, primarily focused on Linux and Database administration. In those years, apart from learning significant technical knowledge, I also became comfortable working in a professional team and adapting to my environment, as I switched through 3 roles in that time.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments