Open In App

Check if a List is Contained in Another List - Python

Last Updated : 01 Jul, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

In Python, it is often useful to check whether all elements of one list exist in another list. This is known as checking if a list is contained in another list. This is commonly used in tasks like filtering, searching and validating data.

For example, given two lists, if every item in the smaller list is present in the larger list (without breaking order), then we say the first list is contained in the second.

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

Let's discuss different methods to solve this.

Using list comprehension 

List comprehension is a concise way to check if all elements of one list appear in the same order within another list. It works by comparing slices of one list to another during iteration.

Python
A = [1, 2]
B = [1, 2, 3, 1, 1, 2, 2]

n = len(A)
r = any(A == B[i:i + n] for i in range(len(B) - n + 1))
print(r)

Output
True

Explanation:

  • B[i:i+n] takes slices of list B of the same length as A.
  • A == B[i:i+n] checks if any slice matches A exactly and in order.
  • any() returns True if at least one match is found.

Using Nested loop  

Using two for loops, one to go through the larger list and another to compare elements of the smaller list at each position. If all elements match in order, it returns True otherwise, False.

Python
A = [1, 2]
B = [1, 2, 3, 1, 1, 2, 2]
f = False

for i in range(len(B) - len(A) + 1):
    for j in range(len(A)):
        if B[i + j] != A[j]:
            break
    else:
        f = True
        break
print(f)

Output
True

Explanation:

  • Outer loop checks all possible starting positions in B where A could fit.
  • Inner loop compares elements in A with corresponding elements in B starting from position i.
  • sets f = True and breaks, meaning match found.

Using Numpy

NumPy compare sublists by turning both lists into arrays and checking if any slice of the larger array matches the smaller one.

Python
import numpy as np
A = ['x', 'y', 'z']
B = ['x', 'a', 'y', 'x', 'b', 'z']
a1 = np.array(A)
b1 = np.array(B)
f = False

for i in range(len(b1)):
    if np.array_equal(a1, b1[i:i+len(a1)]):
        f = True
        break
print(f)

Output
False

Explanation: checks if list A appears as a continuous sublist in list B by converting both to NumPy arrays and comparing slices using np.array_equal. Not found in same order, so False.

Related Articles:


Practice Tags :

Similar Reads