Skip to content
Related Articles

Related Articles

Python | Check if two lists have any element in common

View Discussion
Improve Article
Save Article
  • Last Updated : 24 Sep, 2022
View Discussion
Improve Article
Save Article

Sometimes we encounter the problem of checking if one list contains any element of another list. This kind of problem is quite popular in competitive programming. Let’s discuss various ways to achieve this particular task.

Method #1: Using any() 

Python3




# Python code to check if two lists
# have any element in common
 
# Initialization of list
list1 = [1, 2, 3, 4, 55]
list2 = [2, 3, 90, 22]
 
# using any function
out = any(check in list1 for check in list2)
 
# Checking condition
if out:
    print("True")
else :
    print("False")

Output:

True

 Method #2: Using in operator. 

Python3




# Python code to check if two lists
# have any element in common
 
# Initialization of list
list1 = [1, 3, 4, 55]
list2 = [90, 22]
 
flag = 0
 
# Using in to check element of
# second list into first list
for elem in list2:
    if elem in list1:
        flag = 1
 
# checking condition
if flag == 1:
    print("True")
else :
    print("False")

Output:

False

Method#3: Using set()

Python3




# Python code to check if two lists
# have any element in common
 
# Initialization of list
list1 = [1, 2, 3, 4, 55]
list2 = [2, 3, 90, 22]
 
# using set
out = set(list1) & set(list2)
 
# Checking condition
if out:
    print("True")
else :
    print("False")

Output

True

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!