Based on this answer, I'd like to show how to "early exit" the iteration once the first item containing the substring aa
is encountered. This only returns the first position.
import itertools
first_idx = len(tuple(itertools.takewhile(lambda x: "aa" not in x, mylist)))
This should be much more performant than looping over the whole list when the list is large, since takewhile
will stop once the condition is False
for the first time.
I know that the question asked for all positions, but since there will be many users stumbling upon this question when searching for the first substring, I'll add this answer anyways.