Search code examples
pythonlistrandomindexingsublist

find consecutive items in list


with a list like this:

list = ["A","B","C","D","E","F","G","H","I"]

in Python how to get the index of the first element of a sub-list (consecutive items) in this list.

sub-lists are of variable sizes.

example of sub-lists are:

 ["C","D","E"],["B","C","D","E","F","G"],["G","H"], ...

Solution

  • You can use the following, which assumes that the list, sub_lists are valid:

    def isSublist(entire_list, sub_list):
        return sub_list in [entire_list[i:len(sub_list)+i] for i in range(len(entire_list) - len(sub_list))]
    
    
    all_list = ["A","B","C","D","E","F","G","H","I"]
    sub_lists = [["C","D","E"],["B","C","D","E","F","G"],["G","H"],["B", "D"], ["E"], ["E", "F", "H"]]
    
    res = [all_list.index(l[0]) for l in sub_lists if isSublist(all_list, l)]
    print(res)
    

    Which uses list comprehensions, you can read more on that in the following link:

    https://realpython.com/list-comprehension-python/