Check for a common item in three lists: instead, it checks for identical lists

I need to enter three lists and do a logical check to see if there is a common element for all lists. So far, the bulk of the code looks like this:

def in_all_three(listA, listB, listC): for x in listA: if x in listB and x in listC: return True else: return False 

I don’t know why, but it only returns True if the lists are identical. What is wrong with my code?

+5
source share
2 answers

For this purpose you can use intersection sets .

 def check_common_element(listA, listB, listC): common_elements = set.intersection(set(listA), set(listB), set(listC)) if common_elements: return True else: return False # Test case 1: Testing when there is a common value among lists list_a = [1,2,3] list_b = [1,5,6] list_c = [1,8,9] print(check_common_element(list_a,list_b,list_c)) # output: True # Test case 2: Testing when there is no common value among lists list_a = [1,2,3] list_b = [1,5,6] list_c = [7,8,9] print(check_common_element(list_a,list_b,list_c)) # output: False 

As @ Reti43 suggested, you can do return bool(common_elements) instead of if-else as the best option for the reasons described in the comments below. In this case, the modified function will look like this:

 def check_common_element(listA, listB, listC): common_elements = set.intersection(set(listA), set(listB), set(listC)) return bool(common_elements) 
+4
source

Logically, you need to return False only after all the elements have been checked and no match has been found. For this you need to RETURN FALSE; after completing the cycle.

 def in_all_three(listA, listB, listC): for x in listA: if x in listB and x in listC: return True return False 
+1
source

Source: https://habr.com/ru/post/1272824/


All Articles