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?
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?
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
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!
One can also use the &
operator between two sets.
any(set(array_1) & set(array_2))