How to check if a list is a sublist of another list in Python
How to check if a list is a sublist of another list in Python.
Here's a step-by-step tutorial on how to check if a list is a sublist of another list in Python:
- Start by defining two lists: the main list and the potential sublist. For example:
main_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
sublist = [3, 4, 5]
Next, write a function to check if the sublist is present in the main list. You can name the function
is_sublist
for clarity.Inside the
is_sublist
function, use a loop to iterate through the main_list. You can use therange
function to define the range of indices to check.
def is_sublist(main_list, sublist):
for i in range(len(main_list)):
# code to be added in the next step
- Inside the loop, check if the sublist matches a section of the main list starting from the current index
i
. Use slicing to extract the sublist-like section to compare.
def is_sublist(main_list, sublist):
for i in range(len(main_list)):
if main_list[i:i+len(sublist)] == sublist:
return True
return False
If the sublist is found, return
True
from the function. If the loop completes without finding a match, returnFalse
to indicate that the sublist is not present in the main list.Finally, you can call the
is_sublist
function, passing the main list and the potential sublist as arguments, and store the result in a variable. You can then print the result to see if the sublist is present.
main_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
sublist = [3, 4, 5]
is_sublist_result = is_sublist(main_list, sublist)
print(is_sublist_result)
The output will be True
if the sublist is present in the main list, and False
if it is not.
That's it! You now have a step-by-step tutorial on how to check if a list is a sublist of another list in Python.