Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python – Check for Sublist in List

  • Last Updated : 03 Jul, 2020

Sometimes, while working with Python Lists, we can have a problem in which we need to check if a particular sublist is contained in exact sequence in a list. This task can have application in many domains such as school programming and web development. Let’s discuss certain ways in which this task can be performed.

Input : test_list = [5, 6, 3, 8, 2, 1, 7, 1], sublist = [8, 2, 3]
Output : False

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

Input : test_list = [5, 6, 3, 8, 2, 3, 7, 1], sublist = [8, 2, 3]
Output : True



Method #1 : Using loop + list slicing
The combination of above functions can be used to solve this problem. In this, we perform task of checking for sublist by incremental slicing using list slicing technique.




# Python3 code to demonstrate working of 
# Check for Sublist in List
# Using loop + list slicing
  
# initializing list
test_list = [5, 6, 3, 8, 2, 1, 7, 1]
  
# printing original list 
print("The original list : " + str(test_list))
  
# initializing sublist 
sublist = [8, 2, 1]
  
# Check for Sublist in List
# Using loop + list slicing
res = False
for idx in range(len(test_list) - len(sublist) + 1):
        if test_list[idx : idx + len(sublist)] == sublist:
            res = True 
            break
          
# printing result 
print("Is sublist present in list ? : " + str(res))
Output :
The original list : [5, 6, 3, 8, 2, 1, 7, 1]
Is sublist present in list ? : True

 

Method #2 : Using any() + list slicing + generator expression
The combination of above functions is used to solve this problem. In this, we perform the task of checking for any sublist equating to desired using any() and list slicing is used to slice incremental list of desired length.




# Python3 code to demonstrate working of 
# Check for Sublist in List
# Using any() + list slicing + generator expression
  
# initializing list
test_list = [5, 6, 3, 8, 2, 1, 7, 1]
  
# printing original list 
print("The original list : " + str(test_list))
  
# initializing sublist 
sublist = [8, 2, 1]
  
# Check for Sublist in List
# Using any() + list slicing + generator expression
res = any(test_list[idx : idx + len(sublist)] == sublist
        for idx in range(len(test_list) - len(sublist) + 1))
          
# printing result 
print("Is sublist present in list ? : " + str(res))
Output :
The original list : [5, 6, 3, 8, 2, 1, 7, 1]
Is sublist present in list ? : True



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!