Maybe get a slice of the list if: any(word in line for word in inc_list) = True?
from random import choice
words = ['ant', 'bee', 'cauliflower', 'cow', 'bean']
work01_list = [f'Line {i} stuff line {choice(words)}.\n' for i in range(1,11)]
inc_list = ['bean', 'cauliflower']
for i in range(len(work01_list)):
line = work01_list[i]
if any(word in line for word in inc_list):
list_slice = work01_list[i:i+4]
for w in inc_list:
if w in list_slice[0]:
word = w
for j in list_slice:
print(f'word = {word}, {j}')
print('End of slice ... \n')
# put break here to stop after the first 4 lines
#break
Gribouillis said something about not overlapping. You could do that like this:
work01_gen = (f'Line {i} stuff line {choice(words)}.\n' for i in range(1,31))
for w in work01_gen:
try:
if any(word in w for word in inc_list):
print('Found a wanted word, now printing the next 3 lines ... ')
for i in range(3):
print(next(work01_gen))
except StopIteration:
print('Run out of generator items!')