I have a list for example ['tree', 'water', 'dog', 'soap', 'cat', 'bird', 'tree', 'dog', 'water']
I want a function that takes in any list with a start word and ends word and gives me back sub-lists of them. I want it to search the entire list for the start and end word. So if my start word is tree and end word is water it would give me back two lists consisting of
['tree', water'] and ['tree', 'dog', 'water']. And if there is no word tree or water then the function should just skip it.
I've tried doing
def sublist(words, start, end):
start_index = words.index(start)
end_index = words.index(end)
sublist = words[start_index:end_index+1]
words = ['tree', 'water', 'dog', 'soap', 'cat', 'bird', 'tree', 'dog', 'water']
start = 'tree'
end = 'water'
sublist(words, start, end)
but this only gives back one list of ['tree', 'water']. I want ['tree,' water],['tree', 'dog', 'water'], I don't know how to keep continuing after I find the first segment. It would also error if the start or end word is not on the list.