Manual looping

সাবলিস্ট
সাবলিস্ট Python ট্র্যাকে

This approach uses a helper function that manually loops through the lists to determine if the first list is a sublist of the second one. This approach is the longest one by far, though it may be more comprehensible to some.

SUBLIST = 1
SUPERLIST = 2
EQUAL = 3
UNEQUAL = 4

def check_sub_sequences(list_a, list_b):
    len_a, len_b = len(list_a), len(list_b)
    index_a, index_b = 0, 0
    next_index_b = 1

    while index_a < len_a and index_b < len_b:
        if list_a[index_a] == list_b[index_b]:
            index_a += 1
        else:
            index_a, index_b = 0, next_index_b
            next_index_b += 1
        index_b += 1

    if index_a == len_a:
        if len_a == len_b:
            return EQUAL
        return SUBLIST
    return UNEQUAL

def sublist(list_one, list_two):
    result = check_sub_sequences(list_one, list_two)

    if result == UNEQUAL and check_sub_sequences(list_two, list_one) == SUBLIST:
        result = SUPERLIST
    return result
Note

You might wonder why the lists in the helper function are named list_a and list_b instead of list_one and list_two. This is because if the parameters have the same name, Pylint thinks the parameters are being passed in incorrectly when we call check_sub_sequences(list_two, list_one). (The exact warning generated is W1114 arguments-out-of-order.)

In this approach, the first thing sublist() does is call the helper function. That function then loops through the lists, keeping track of an index for both lists so it can test all necessary combinations to determine if list_one is a sublist of list_two.

However, the helper function only determines if list_one is equal to or a sublist of list_two, not if list_one is a superlist of list_two. That is why if the helper function returns UNEQUAL, sublist() needs to make sure that it isn't acutally a superlist.

sublist() does this by calling the helper function with its arguments reversed: check_sub_sequences(list_two, list_one). If the result is SUBLIST, that means list_two is a sublist of list_one, thus list_one must be a superlist of list_two.

Thus all possibilities are covered, and sublist() returns the result.

7 অক্টোবর 2026 · কাজে লেগেছে?