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

Last Updated : 10 May, 2023

Summarize

Comments

Improve

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:

TrueFalse

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



S

Smitha Dinesh Semwal

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

Improve

Next Article

Python Check if the List Contains Elements of another List

Please Login to comment...

Python | Check if a list is contained in another list - GeeksforGeeks (2024)
Top Articles
A comprehensive guide on how to change NAT type on Xbox One
Top 5 Things You Should Never Do at an Auction - JD's Realty
Skyward Sinton
Roblox Roguelike
The 10 Best Restaurants In Freiburg Germany
Toyota Campers For Sale Craigslist
Google Sites Classroom 6X
Seething Storm 5E
Kristine Leahy Spouse
Stl Craiglist
Vanadium Conan Exiles
10000 Divided By 5
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Gma Deals And Steals Today 2022
Dr. med. Uta Krieg-Oehme - Lesen Sie Erfahrungsberichte und vereinbaren Sie einen Termin
Napa Autocare Locator
Who called you from +19192464227 (9192464227): 5 reviews
Aspen Mobile Login Help
Walgreens Tanque Verde And Catalina Hwy
20 Different Cat Sounds and What They Mean
Sodium azide 1% in aqueous solution
Jail View Sumter
Slim Thug’s Wealth and Wellness: A Journey Beyond Music
Gas Buddy Prices Near Me Zip Code
Living Shard Calamity
Colonial Executive Park - CRE Consultants
Beaufort 72 Hour
Margaret Shelton Jeopardy Age
Xxn Abbreviation List 2017 Pdf
Netspend Ssi Deposit Dates For 2022 November
Ordensfrau: Der Tod ist die Geburt in ein Leben bei Gott
Current Students - Pace University Online
Tripcheck Oregon Map
Mia Malkova Bio, Net Worth, Age & More - Magzica
James Ingram | Biography, Songs, Hits, & Cause of Death
Mg Char Grill
4083519708
Domina Scarlett Ct
Electronic Music Duo Daft Punk Announces Split After Nearly 3 Decades
Achieving and Maintaining 10% Body Fat
Devon Lannigan Obituary
Dr Mayy Deadrick Paradise Valley
Advance Auto.parts Near Me
22 Golden Rules for Fitness Beginners – Barnes Corner Fitness
Yourcuteelena
Spreading Unverified Info Crossword Clue
Santa Ana Immigration Court Webex
Read Love in Orbit - Chapter 2 - Page 974 | MangaBuddy
Festival Gas Rewards Log In
Edict Of Force Poe
Bones And All Showtimes Near Emagine Canton
Texas Lottery Daily 4 Winning Numbers
Latest Posts
Article information

Author: Kerri Lueilwitz

Last Updated:

Views: 5953

Rating: 4.7 / 5 (67 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Kerri Lueilwitz

Birthday: 1992-10-31

Address: Suite 878 3699 Chantelle Roads, Colebury, NC 68599

Phone: +6111989609516

Job: Chief Farming Manager

Hobby: Mycology, Stone skipping, Dowsing, Whittling, Taxidermy, Sand art, Roller skating

Introduction: My name is Kerri Lueilwitz, I am a courageous, gentle, quaint, thankful, outstanding, brave, vast person who loves writing and wants to share my knowledge and understanding with you.