In: Computer Science
Given two lists, write python code to print “True” if the two lists have at least one common element. For example, x = [1,2,3], y=[3,4,5], then the program should print “True” since there is a common element 3.
Code 1:
def common_elements(L1, L2):
    outcome = False
  
    for a in L1:
     # traversal of L1 i.e, 1st list
  
        for b in L2: #
traversal of L2 i.e, 2nd list
    
            if
a == b:
         #Checking if
common element preset, if present
                outcome
= True
                return
outcome
                  
    return outcome
      
# Driver code
L1 = list()
L2 = list()
size1 = int(input("enter size of L1:"))
print("Enter the elements of L1:")
for a in range(int(size1)): #creating an list of required
size
   x = int(input(""))
        #storing input
elements in list L1
   L1.append(x)
size2 = int(input("Enter size of L2:"))
print("Enter the elements of L2:")
for a in range(int(size2)):   #creating an list of
required size
   x = int(input(""))
          #storing
input elements in list L1
   L2.append(x)
print(common_elements(L1, L2)) #Print the result
----------------------------------------------------------------------------------------------------------------
Snapshot of Code and Output:


CODE 2: (Taking input lists directly)
def common_elements(L1, L2):
outcome = False
  
for a in L1: # traversal of L1 i.e, 1st list
  
for b in L2: # traversal of L2 i.e, 2nd list
  
if a == b: #Checking if common element preset, if present
outcome = True
return outcome
  
return outcome
  
#Driver Code
L1 = [1, 2, 3]
L2 = [3, 4, 5]
print(common_elements(L1, L2))
  
L1 = [1, 2, 3]
L2 = [4, 5, 6]
print(common_elements(L1, L2))
Snapshot of Code and Output:
