Home > front end >  Check if an array contains any element of another array in Python [duplicate]
Check if an array contains any element of another array in Python [duplicate]

Time:10-05

a = [1, 2, 3]
b = [4, 5, 1]

I need to check if one (or more) elements are common in both arrays.

CodePudding user response:

Check the intersections of the sets and get the boolean:

>>> bool(set(a) & set(b))
True
>>> 

Or not not:

>>> not not (set(a) & set(b))
True
>>> 

Or just with any:

>>> any(i in b for i in a)
True
>>> 

CodePudding user response:

this is simple intersection concept which we used to learn in maths well here I have tried to demonstrate the function which take common from two list and return new list with common elements

    def intersection(lst1, lst2):
        lst3 = [value for value in lst1 if value in lst2]
        return lst3
    
    
    a = [1, 2, 3]
    b = [4, 5, 1]
    
    print(intersection(a,b))
  • Related