Python | Check if two lists have at least one element in common

Python Methods and Functions

Examples :

 Input: a = [1, 2, 3, 4, 5] b = [5, 6, 7, 8, 9] Output: True Input: a = [1, 2, 3, 4, 5] b = [6, 7, 8, 9] Output: False 

Method 1: bypass list

By using traversal on two lists, we can check if there is at least one common element in them. When traversing two lists, if we find one element in common, we return true. After a full traversal and validation, if the elements don`t match, we return false.

# Python program to check
# if two lists have at least
# one element in common
# use a bypass list

 

def common_data (list1, list2):

  result = False

 

# move in first list

for x in list1:

 

# move in the second list

for y in list2:

 

#if one common

if x = = y:

result = True

return result 

 

return result

 
# driver code

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

b = [ 5 , 6 , 7 , 8 , 9 ]

print (common_data (a, b))

 

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

b = [ 6 , 7 , 8 , 9 ]

print (common_data (a, b))

Exit :

 True Fa lse 

Method 2. Using Set and Property

Using set and property if there is at least one common element, then set (a) & amp; set (b) returns a positive integer, if it does not contain a positive integer then it returns 0. So we insert a into set_a and b into set_b and then check if set_a & amp; set_b for a positive integer or not.

# Python program to check
# if two lists have at least
# one common element
# using a set and property

 

def common_member (a , b):

a_set = set (a)

b_set = set ( b)

if (a_set & amp ; b_set):

return True  

else :

return False

 

 

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

b = [ 5 , , 7 , 8 , 9 ]

print (common_member (a, b))

  

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

b = [ 6 , 7 , 8 , 9 ]

print (common_member (a, b))

Exit:

 True False 

Method 3: using set intersection

Using built-in function set intersections . a_set.intersection (b_set) returns a positive integer if there is at least one common element, otherwise it returns 0. So we insert a in set_a and b in set_b and then check a_set.intersection (b_set) and return depending on the value .

# Python program to check
# if two lists have at least
# one element common
# using intersection set

 

def common_member (a, b):

a_set = set (a)

b_set = set (b)

if len (a_set. intersection (b_set)) & gt;  0 :

return ( True

return ( False

 

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

b = [ 5 , 6 , 7 , 8 , 9 ]

print (common_member (a, b))

 

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

b = [ 6 , 7 , 8 , 9 ]

print (common_member (a, b))

Exit:

 True False 




Get Solution for free from DataCamp guru