0

I have two arrays

array_1 = ["AAAA","BBBB"]
array_2 = ["XXX","AA","AAAA","ZZZZ"]

I want to compare there both arrays and return true if any element from array_1 matches with one in array_2.

How can I do that?

Michael Ruth
  • 2,938
  • 1
  • 20
  • 27
Bella_18
  • 624
  • 1
  • 14

4 Answers4

2
print(any(x in array_2 for x in array_1))
user19077881
  • 3,643
  • 2
  • 3
  • 14
1

The answers given by Barmar and the second user are MUCH more graceful than the function I created. Those answers are single line statements that will result in a value of True or False if printed or assigned to a variable. A much more verbose and entry level function that you may understand a little easier would be something like this (I realize it is elementary but the user asking the question may better understand the comparison with this function):

    def lists_share_element(list1, list2):
        if isinstance(array_1, list) and isinstance(array_2, list):
            if len(list1) > len(list2):
                for item in list1:
            if item in list2:
                return True
            
        elif len(list1) < len(list2):
            for item in list2:
                if item in list1:
                    return True
        else:
            for item in list1:
                if item in list2:
                    return True
        
        return False
BrokenTek
  • 11
  • 4
1
array_1 = ["AAAA","BBBB"]
array_2 = ["XXX","AA","AAAA","ZZZZ"]

match_found = False

for element in array_1:
    if element in array_2:
        match_found = True
        break

if match_found:
    print("Match found")
else:
    print("Match not found")

This code works by iterating through the elements of array_1 and checking if each element is present in array_2. If a match is found, the loop is terminated and the match_found variable is set to True. If the loop completes without finding a match, the match_found variable will remain False. The final step is to check the value of match_found and print the appropriate message.

hope this helps you!

1

One can also use the & operator between two sets.

any(set(array_1) & set(array_2))
AboAmmar
  • 5,439
  • 2
  • 13
  • 24