Python - Check if two lists have any element in common

PythonServer Side ProgrammingProgramming

During manipulating data using python lists, we come across a situation where we need to know if two lists are entirely different from each other or they have any element in common. This can be found out by comparing the elements in the two lists with the below approaches decribed.

Using In

In a for loop we use the in clause to check in an element is present in the list or not. We will stretch this logic to compare the elements of the lists by choosing an element from first list and checking its presence in the second list. So we will have nested for loop to do this check.

Example

 Live Demo

#Declaring lists
list1=['a',4,'%','d','e']
list2=[3,'f',6,'d','e',3]
list3=[12,3,12,15,14,15,17]
list4=[12,42,41,12,41,12]

# In[23]:

#Defining function to check for common elements in two lists
def commonelems(x,y):
   common=0
   for value in x:
      if value in y:
         common=1
   if(not common):
      return ("The lists have no common elements")
   else:
   return ("The lists have common elements")

# In[24]:

#Checking two lists for common elements
print("Comparing list1 and list2:")
print(commonelems(list1,list2))
print("\n")
print("Comparing list1 and list3:")
print(commonelems(list1,list3))
print("\n")
print("Comparing list3 and list4:")
print(commonelems(list3,list4))

Running the above code gives us the following result

Output

Comparing list1 and list2:
The lists have common elements
Comparing list1 and list3:
The lists have no common elements
Comparing list3 and list4:
The lists have common elements

Using sets

Another approach to find, if two lists have common elements is to use sets. The sets have unordered collection of unique elements. So we convert the lists into sets and then create a new set by combining the given sets. If they have some common elements then the new set will not be empty.

Example

 Live Demo

list1=['a',4,'%','d','e']
list2=[3,'f',6,'d','e',3]

# Defining function two check common elements in two lists by converting to sets
def commonelem_set(z, x):
   one = set(z)
   two = set(x)
   if (one & two):
      return ("There are common elements in both lists:", one & two)
   else:
   return ("There are no common elements")

# Checking common elements in two lists for
z = commonelem_set(list1, list2)
print(z)

def commonelem_any(a, b):
out = any(check in a for check in b)

# Checking condition
   if out:
      return ("The lists have common elements.")
   else:
   return ("The lists do not have common elements.")

print(commonelem_any(list1, list2))

Running the above code gives us the following result

Output

('There are common elements in both lists:', {'d', 'e'})
The lists have common elements.
raja
Published on 23-Dec-2019 14:32:14
Advertisements