Python - Check if two lists have any element in common

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.


 Live Demo

#Declaring lists

# In[23]:

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

# In[24]:

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

Running the above code gives us the following result


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.


 Live Demo


# 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)
   return ("There are no common elements")

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

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

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

print(commonelem_any(list1, list2))

Running the above code gives us the following result


('There are common elements in both lists:', {'d', 'e'})
The lists have common elements.

Updated on: 23-Dec-2019

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started