Python | Check if a list is contained in another list - GeeksforGeeks

Python | Check if a list is contained in another list

Last Updated : 10 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given two lists A and B, write a Python program to Check if list A is contained in list B without breaking A’s order. 

Examples:

Input : A = [1, 2], B = [1, 2, 3, 1, 1, 2, 2]
Output : True
Input : A = ['x', 'y', 'z'], B = ['x', 'a', 'y', 'x', 'b', 'z']
Output : False

Approach #1: Naive Approach 

A simple naive approach is to use two for loops and check if the whole list A is contained within list B or not. If such a position is met in list A, then break the loop and return true, otherwise false.

Python3




# Python3 program to Check if a list is
# contained in another list without breaking order
 
# Function
def removeElements(A, B):
     
    for i in range(len(B)-len(A)+1):
        for j in range(len(A)):
            if B[i + j] != A[j]:
                break
        else:
            return True
     
    return False
 
# Initializing lists  
A = [1, 2]
B = [1, 2, 3, 1, 1, 2, 2]
 
# Printing result
print(removeElements(A, B))


Output:

True

Time Complexity: O(n*n)
Auxiliary Space: O(1)

Approach #2: Using list comprehension 

A more efficient approach is to use List comprehension. We first initialize ‘n’ with the length of A. Now use a for loop till len(B)-n and check in each iteration if A == B[i:i+n] or not. 

Python3




# Python3 program to Remove elements of
# list that repeated less than k times
def removeElements(A, B):
    n = len(A)
    return any(A == B[i:i + n] for i in range(len(B)-n + 1))
 
# Initializing lists
A = [1, 2]
B = [1, 2, 3, 1, 1, 2, 2]
 
print(removeElements(A, B))


Output:

True

Time complexity: O(n^2). where A and B are both of length n,
Auxiliary space: O(n), where n is the length of B.

Approach #3: Using join and map module 

Here we use join to join both lists to strings and then use in operator to check if list A is contained in B or not. 

Python3




# Python3 program to Remove elements of
# list that repeated less than k times
def removeElements(A, B):
    return ', '.join(map(str, A)) in ', '.join(map(str, B))
 
 
# Initializing lists
A = ['x', 'y', 'z']
B = ['x', 'a', 'y', 'x', 'b', 'z']
 
print(removeElements(A, B))


Output:

False

Time complexity: O(m*n) , where m is the length of A and n is the length of B.
Auxiliary space: O(1),where m is length of A and n is the length of B.

Approach #4: Using regular expressions 

To check if a list is contained in another list using the Python re (regular expression) module, you can use the re.findall() function to find all instances of list A within list B as a string. If the number of instances found is greater than 0, it means that list A is contained within list B.

Here is an example of how this can be done:

Python3




import re
 
 
def check_list_contained(A, B):
  # convert list A to string
    A_str = ' '.join(map(str, A))
    # convert list B to string
    B_str = ' '.join(map(str, B))
    # find all instances of A within B
    instances = re.findall(A_str, B_str)
 
    # return True if any instances were found, False otherwise
    return len(instances) > 0
 
 
# Initializing lists
A = ['x', 'y', 'z']
B = ['x', 'a', 'y', 'x', 'b', 'z']
 
print(check_list_contained(A, B))
 
# This code is contributed by Edula Vinay Kumar Reddy


Output

False

Time complexity: O(m*n) , where m is length of A and n is length of B.
Auxiliary space: O(1), where m is length of A and n is length of B.

Approach #5: Using Recursive method

Steps:

  1. If list A is empty, return True, as an empty list is always a sublist of any list.
  2. If list B is empty, return False, as an empty list cannot contain any sublist.
  3. If A[0] matches B[0], recursively check the rest of the elements of A and B by calling the is_sublist method with A[1:] and B[1:].
  4. If A[0] does not match B[0], recursively check if A is a sublist of the remaining elements of B by calling the is_sublist method with A and B[1:]
  5. Return True if the previous recursive call returned True, indicating that A is a sublist of B, or False otherwise.

Python3




def is_sublist(A, B):
    if not A:
        return True
    if not B:
        return False
    if A[0] == B[0]:
        return is_sublist(A[1:], B[1:])
    return is_sublist(A, B[1:])
 
 
# Initializing lists
A = [1, 2]
B = [1, 2, 3, 1, 1, 2, 2]
 
res = is_sublist(A, B)
 
# Printing the result
print(res)
 
# This code contributed by tvsk


Output

True

Time complexity: O(n * m), where n is the length of list A and m is the length of list B. This is because the function needs to traverse both lists in the worst-case scenario, and the length of list B may need to be traversed multiple times depending on the position of the matching element of A.

Auxiliary space: O(max(n, m)), where n is the length of list A and m is the length of list B. This is because the function makes recursive calls, and each call adds a new stack frame to the call stack, potentially using up additional memory. However, the maximum depth of the call stack is bounded by the maximum length of A or B, so the space used is proportional to the maximum of the two lengths.

Approach #6: Using Numpy

Note: install numpy module using command “pip install numpy”

Steps:

  1. Import numpy module and define a function named “check_list_contained” that takes two parameters, “A” and “B”.
  2. Convert “A” and “B” to numpy arrays “A_arr” and “B_arr” respectively.
  3. Loop through “B_arr” using a for loop and range function for index “i” in range of length of “B_arr”.
  4. Check if the subarray of “B_arr” starting from index “i” and of length equal to the length of “A_arr” is equal to “A_arr” using the numpy array_equal() function.
  5. If the above condition is true, then return True, as the list “A” is contained in the list “B”.
  6. If the loop finishes execution without returning True, return False, as the list “A” is not contained in the list “B”.
  7. Test the function by passing two list parameters “A” and “B”.
  8. Print the result of the function call.

Python3




import numpy as np
 
 
def check_list_contained(A, B):
 
  # convert list A to numpy array
    A_arr = np.array(A)
    # convert list B to numpy array
    B_arr = np.array(B)
 
    for i in range(len(B_arr)):
        if np.array_equal(A_arr, B_arr[i:i+len(A_arr)]):
            return True
    return False
 
 
# Initializing lists
A = [1, 2]
B = [1, 2, 3, 1, 1, 2, 2]
 
print(check_list_contained(A, B))
 
A = ['x', 'y', 'z']
B = ['x', 'a', 'y', 'x', 'b', 'z']
 
print(check_list_contained(A, B))


Output:

True
False

Time complexity: O(n^2), where n is the length of B.
Auxiliary space: O(n), where n is the length of B.



Similar Reads

Retrieving And Updating Data Contained in Shelve in Python
In Python shelve you access the keys randomly. In order to access the keys randomly in python shelve we use open() function. This function works a lot like the file open() function in File handling. Syntax for open the file using Python shelve shelve.open(filename, flag='c' , writeback=True) In Order to access the keys randomly in shelve in Python,
3 min read
Python | Check if a nested list is a subset of another nested list
Given two lists list1 and list2, check if list2 is a subset of list1 and return True or False accordingly. Examples: Input : list1 = [[2, 3, 1], [4, 5], [6, 8]] list2 = [[4, 5], [6, 8]] Output : True Input : list1 = [['a', 'b'], ['e'], ['c', 'd']] list2 = [['g']] Output : False Let's discuss few approaches to solve the problem. Approach #1 : Naive
7 min read
Python Check if the List Contains Elements of another List
In Python programming, there can be a case where we have to check whether a list contains elements of Another List or not. In that case, we can follow several approaches for doing so. In this article, we will be discussing several approaches to check whether a list contains elements of another list or not. Python List Contains Elements of another L
2 min read
PyQt5 - Check box checked state depending upon another check box
Sometimes while creating a GUI(Graphical User Interface) application there is a need to make lot of check boxes, and some check box depend upon the previous check box for example there are two following check box first check box is "Do you have Laptop ?" and second check box is "Your laptop has i7 Processor?" Here we can see that if first check box
3 min read
Python | Insert list in another list
The problem of inserting a number at any index is a quite common one. But sometimes we require to insert the whole list into another list. These kinds of problems occur in Machine Learning while playing with data. Let's discuss certain ways in which this problem can be solved. Method #1: Using insert() + loop In this method, we insert one element b
8 min read
Python | Update a list of tuples using another list
Given two list of tuples, write a Python program to update 'list1' according to the 'list2' and return an updated list. Examples: Input : list1 = [('x', 0), ('y', 5)] list2 = [('x', 100), ('y', 200)] Output : [('x', 100), ('y', 200)] Input : list1 = [('a', 0), ('b', 0), ('c', 0)] list2 = [('a', 1), ('b', 2)] Output :[('a', 1), ('b', 2), ('c', 0)] A
4 min read
Python | Move one list element to another list
Sometimes, while working with Python list, there can be a problem in which we need to perform the inter list shifts of elements. Having a solution to this problem is always very useful. Let's discuss certain way in which this task can be performed. Method : Using pop() + insert() + index() This particular task can be performed using combination of
6 min read
Python program to get the indices of each element of one list in another list
Given 2 lists, get all the indices of all occurrence of each element in list2 from list1. Input : test_list = [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3], get_list = [7, 5, 4] Output : [[3], [1, 9], [0, 7]] Explanation : 5 is present at 1st and 9th index. Input : test_list = [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3], get_list = [7, 5, 8] Output : [[3], [1, 9],
7 min read
Python program to mask a list using values from another list
Given two lists, the task is to write a python program that marks 1 for elements present in the other list else mark 0. Input : test_list = [5, 2, 1, 9, 8, 0, 4], search_list = [1, 10, 8, 3, 9]Output : [0, 0, 1, 1, 1, 0, 0]Explanation : 1, 9, 8 are present in test_list at position 2, 3, 4 and are masked by 1. Rest are masked by 0. Input : test_list
5 min read
Python Program To Merge A Linked List Into Another Linked List At Alternate Positions
Given two linked lists, insert nodes of the second list into the first list at alternate positions of the first list. For example, if first list is 5->7->17->13->11 and second is 12->10->2->4->6, the first list should become 5->12->7->10->17->2->13->4->11->6 and second list should become empty. The
3 min read
Practice Tags :