Get first list index containing sub-string?

Variation of abyx solution (optimised to stop when the match is found)

def first_substring(strings, substring):
    return next(i for i, string in enumerate(strings) if substring in string)

If you are pre 2.6 you'll need to put the next() at the end

def first_substring(strings, substring):
    return (i for i, string in enumerate(strings) if substring in string).next()

A non-slicky method:

def index_containing_substring(the_list, substring):
    for i, s in enumerate(the_list):
        if substring in s:
              return i
    return -1

With a one-liner:

index = [idx for idx, s in enumerate(l) if 'tiger' in s][0]

Tags:

Python

List