Check for Sublist in List-Python
Last Updated :
26 Feb, 2025
The task of checking for a sublist in a list in Python involves determining whether a given sequence of elements (sublist) appears consecutively within a larger list. This is a common problem in programming, particularly in data processing and pattern matching. For example, if we have a list [5, 6, 3, 8, 2, 1, 7, 1] and a sublist [8, 2, 1], we need to check if the exact sequence [8, 2, 1] exists in the larger list.
Using str.join()
This approach converts the list into a comma-separated string and uses find() to locate the sublist pattern. Since string search operations are optimized in Python, this method is often the fastest for medium to large lists.
Python
a = [5, 6, 3, 8, 2, 1, 7, 1]
b = [8, 2, 1] # sublist
# Convert to string representation
a_str = ','.join(map(str, a))
b_str = ','.join(map(str, b))
res = a_str.find(b_str) != -1
print(res)
Explanation: This code checks if sublist b is present in list a by converting both lists into comma-separated strings. The main list a becomes '5,6,3,8,2,1,7,1' and the sublist b becomes '8,2,1'. It then uses the find() method to check if b_str is a substring of a_str. If found, find() returns the index otherwise, -1.
Using collections.deque
By maintaining a sliding window using deque, this technique efficiently checks for the sublist without creating new slices repeatedly. Ideal for large lists or streaming data, as deque allows fast appending and popping operations.
Python
from collections import deque
a = [5, 6, 3, 8, 2, 1, 7, 1]
b = [8, 2, 1] # sublist
# convert sublist to tuple
b_tuple = tuple(b)
window = deque(a[:len(b) - 1], maxlen=len(b))
res = False
for i in range(len(b) - 1, len(a)):
window.append(a[i])
if tuple(window) == b_tuple:
res = True
break
print(res)
Explanation: A deque window with a maximum length equal to b is initialized using the first len(b) - 1 elements of a. The loop then starts from len(b) - 1 to the end of a, appending each element to the window. With each addition, the oldest element is automatically removed. The window is converted to a tuple and compared to b_tuple. If they match, res is set to True and the loop breaks.
Using in operator
This method turns both lists into string representations and uses the in keyword to check for the sublist. While easy to read, it can be slightly slower compared to find() but works well for small to medium lists.
Python
a = [5, 6, 3, 8, 2, 1, 7, 1]
b = [8, 2, 1] # sublist
res = str(b)[1:-1] in str(a)[1:-1]
print(res)
Explanation: str(b) returns the string "[8, 2, 1]" and str(a) returns "[5, 6, 3, 8, 2, 1, 7, 1]". To remove the square brackets, slicing [1:-1] is used, resulting in "8, 2, 1" and "5, 6, 3, 8, 2, 1, 7, 1". The in operator checks if the string of b is a substring of the string of a. If it is, res is True otherwise False.
Using for loop
The most efficient method, it iterates through the list and compares each slice with the sublist. While easy to implement, it is the least efficient for large lists due to repeated slicing operations, but remains a common choice for beginners and small lists.
Python
a = [5, 6, 3, 8, 2, 1, 7, 1]
b = [8, 2, 1] # sublist
res = False # boolean variable
for idx in range(len(a) - len(b) + 1):
if a[idx: idx + len(b)] == b:
res = True
break
print(res)
Explanation: loop iterates over possible starting indices in a, from 0 to len(a) - len(b), ensuring that the slice will not go out of bounds. In each iteration, a sublist of length equal to b is extracted from a using slicing a[idx: idx + len(b)]. This sublist is compared to b. If they match, res is set to True and the loop is terminated using break.
Similar Reads
Python | Test for False list Sometimes, we need to check if a list is completely True of False, these occurrences come more often in testing purposes after the development phase. Hence, having a knowledge of all this is necessary and useful. Lets discuss certain ways in which this can be performed. Method #1: Naive Method In th
8 min read
Python - Count frequency of Sublist in given list Given a List and a sublist, count occurrence of sublist in list. Input : test_list = [4, 5, 3, 5, 7, 8, 3, 5, 7, 2, 3, 5, 7], sublist = [3, 5, 7] Output : 3 Explanation : 3, 5, 7 occurs 3 times. Input : test_list = [4, 5, 3, 5, 8, 8, 3, 2, 7, 2, 3, 6, 7], sublist = [3, 5, 7] Output : 0 Explanation :
3 min read
Python | Check for Descending Sorted List The sorted operation of list is essential operation in many application. But it takes best of O(nlogn) time complexity, hence one hopes to avoid this. So, to check if this is required or not, knowing if list is by default reverse sorted or not, one can check if list is sorted or not. Lets discuss va
3 min read
Python - Check if tuple list has all K Sometimes, while working with Python records, we can have a problem in which we need to test if all the elements in tuples of tuple list are K. This problem can have applications in many data domains such as Machine Learning and Web development. Let's discuss certain ways in which this task can be p
7 min read
Python - Check for None value in Matrix Python supports a list as its list element and hence a matrix can be formed. Sometimes we might have a utility in which we require to perform None check in that list of list i.e matrix and its a very common in all the domains of coding, especially Data Science. Letâs discuss certain ways in which th
5 min read