Open In App

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

Last Updated : 13 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given two lists a, b. Check if two lists have at least one element common in them. 

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: Traversal of List

Using traversal in two lists, we can check if there exists one common element at least in them. While traversing two lists if we find one element to be common in them, then we return true. After complete traversal and checking, if no elements are same, then we return false. 

Python




# Python program to check
# if two lists have at-least
# one element common
# using traversal of list
 
def common_data(list1, list2):
    result = False
 
    # traverse in the 1st list
    for x in list1:
 
        # traverse in the 2nd 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))


Output:

True 
False

Time complexity: O(n*m), where n and m are the lengths of the input lists.
Auxiliary space: O(1).

Method 2 : Using Set and Property

Using set’s and property, if there exists at least one common element then set(a)&set(b) returns a positive integer, if it does not contains any positive integer, then it returns 0. So we insert a in set_a and b in set_b and then check if set_a & set_b for a positive integer or not. 

Python




# Python program to check
# if two lists have at-least
# one element common
# using set and property
 
def common_member(a, b):
    a_set = set(a)
    b_set = set(b)
    if (a_set & b_set):
        return True
    else:
        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))


Output:

True 
False

Time complexity: O(m + n), where m and n are the lengths of the input lists a and b, respectively.
Auxiliary space: O(m + n), for creating the two sets a_set and b_set.

Method 3 : Using Set Intersection

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

Python




# Python program to check
# if two lists have at-least
# one element common
# using set intersection
 
def common_member(a, b):
    a_set = set(a)
    b_set = set(b)
    if len(a_set.intersection(b_set)) > 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))


Output:

True 
False

Time complexity: O(n), where n is the size of the larger list between a and b. 
Auxiliary space: O(n), where n is the size of the larger list between a and b.

Another approach that can be used to check if two lists have at least one common element is to use the Counter class from the collections module. The Counter class is a subclass of dict that is used to count the occurrences of elements in a list.

Here is an example of how the Counter class can be used to check if two lists have at least one common element:

Python3




from collections import Counter
 
def have_common_element(list1, list2):
    counter1 = Counter(list1)
    counter2 = Counter(list2)
    for element, count in counter1.items():
        if element in counter2 and count > 0:
            return True
    return False
 
a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
print(have_common_element(a, b))  # True
 
a = [1, 2, 3, 4, 5]
b = [6, 7, 8, 9]
print(have_common_element(a, b))  # False


Output

True
False

Time complexity: O(n+m), where n is the length of list1 and m is the length of list2.

Auxiliary space: O(k), where k is the number of unique elements in both lists combined. 

Method #5 : Using operator.countOf() method

Python3




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


Output

True

Time Complexity: O(N)
Auxiliary Space: O(1)

Method 4: Using the any() function and the list comprehension method.

This methos uses the any() function along with list comprehension to check if two lists have at least one common element. The list comprehension creates a list of boolean values by comparing each element of the first list to each element of the second list. The any() function returns True if at least one of the boolean values in the list is True, indicating that there is at least one common element between the two lists.

Algorithm:

Create a boolean list using list comprehension that compares each element of the first list to each element of the second list.
Check if any() of the boolean values in the list is True.
If any() is True, return True. Otherwise, return False.

Python3




def common_member(a, b):
    return any(i in b for i in a)
  
a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
print(common_member(a, b))  # True
  
a =[1, 2, 3, 4, 5]
b =[6, 7, 8, 9]
print(common_member(a, b))  # False


Output

True
False

Time complexity: O(n*m), where n and m are the lengths of the input lists.
Auxiliary space: O(1).



Similar Reads

Python | Check if two lists have any element in common
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() C/C++ Code # Python code to check if two lists # have any element in common # Initialization of list lis
5 min read
Python program to check if a string has at least one letter and one number
Given a string in Python. The task is to check whether the string has at least one letter(character) and one number. Return “True” if the given string fully fill the above condition else return “False” (without quotes). Examples: Input: welcome2ourcountry34 Output: True Input: stringwithoutnum Output: False Approach: The approach is simple we will
4 min read
How to Zip two lists of lists in Python?
The normal zip function allows us the functionality to aggregate the values in a container. But sometimes, we have a requirement in which we require to have multiple lists and containing lists as index elements and we need to merge/zip them together. This is quite uncommon problem, but solution to it can still be handy. Let's discuss certain ways i
7 min read
Python | Print all the common elements of two lists
Given two lists, print all the common elements of two lists. Examples: Input : list1 = [1, 2, 3, 4, 5] list2 = [5, 6, 7, 8, 9] Output : {5} Explanation: The common element of the lists is 5. Input : list1 = [1, 2, 3, 4, 5] list2 = [6, 7, 8, 9] Output : No common elements Explanation: They do not have any elements in common in between them Method 1:
8 min read
Python - Check if all tuples have element difference less than K
Given a Tuple list, check if each tuple has a difference less than K. Input : test_list = [(3, 4), (1, 2), (7, 8), (9, 13)], K = 2 Output : False Explanation : 13 - 9 = 4 > 2. Input : test_list = [(3, 4), (1, 2), (7, 8)], K = 2Output : True Explanation : All have abs. diff 1 < 2. Method #1 : Using loop In this, we keep a boolean variable and
7 min read
Python | Program to count number of lists in a list of lists
Given a list of lists, write a Python program to count the number of lists contained within the list of lists. Examples: Input : [[1, 2, 3], [4, 5], [6, 7, 8, 9]] Output : 3 Input : [[1], ['Bob'], ['Delhi'], ['x', 'y']] Output : 4 Method #1 : Using len() C/C++ Code # Python3 program to Count number # of lists in a list of lists def countList(lst):
5 min read
Python - Convert Lists into Similar key value lists
Given two lists, one of key and other values, convert it to dictionary with list values, if keys map to different values on basis of index, add in its value list. Input : test_list1 = [5, 6, 6, 6], test_list2 = [8, 3, 2, 9] Output : {5: [8], 6: [3, 2, 9]} Explanation : Elements with index 6 in corresponding list, are mapped to 6. Input : test_list1
12 min read
Indexing Lists Of Lists In Python
Lists of lists are a common data structure in Python, providing a versatile way to organize and manipulate data. When working with nested lists, it's crucial to understand how to index and access elements efficiently. In this article, we will explore three methods to index lists of lists in Python using the creation of a sample list, followed by ex
3 min read
Python program to find common elements in three lists using sets
Prerequisite: Sets in Python Given three arrays, we have to find common elements in three sorted lists using sets. Examples : Input : ar1 = [1, 5, 10, 20, 40, 80] ar2 = [6, 7, 20, 80, 100] ar3 = [3, 4, 15, 20, 30, 70, 80, 120] Output : [80, 20] Input : ar1 = [1, 5, 5] ar2 = [3, 4, 5, 5, 10] ar3 = [5, 5, 10, 20] Output : [5] Method 1: We have given
5 min read
Python | Find common elements in list of lists
The problem of finding the common elements in list of 2 lists is quite a common problem and can be dealt with ease and also has been discussed before many times. But sometimes, we require to find the elements that are in common from N lists. Let's discuss certain ways in which this operation can be performed. Method #1 : Using reduce() + lambda + s
6 min read
three90RightbarBannerImg