Search code examples
pythonlistsublist

Python: Find a sublist in a list, and print the next element in the list


I have two lists like this

#Main List
    0       1        2      3        4      5       6        7       8       9       10       11
['blue', 'crash', 'pink', 'pink', 'gold', 'blue', 'blue', 'crash', 'pink', 'pink', 'gold', 'blue']
    #Sublist

['crash', 'pink', 'pink', 'gold'] 

I wish to find the sublist in the main list (if it exists). If found, I wish to print the next occurring element in the list.

For instance, for the two lists above, I wish to have this as an output:

'blue'
'blue'

the first 'blue' comes from the 5th element of the list, which is located just after the first occurrence of the sublist (L[0:4]). The second 'blue' comes from the 11th element of the main list, which is also located after the second occurrence of the substring in the List.


Solution

  • You can loop over the list, look for the sublist and print the next element if it's found:

    List = ['blue', 'crash', 'pink', 'pink', 'gold', 'blue', 'blue', 'crash', 'pink', 'pink', 'gold', 'blue']
    Sublist = ['crash', 'pink', 'pink', 'gold']
    
    for i in range(len(List)-len(Sublist)): #Loop over the List
        if List[i:i+len(Sublist)] == Sublist:  #If we find the sublist in the List
                print(List[i+len(Sublist)])    #we print it