Find all instances of a sub-string in a list of strings and return the index of the string where the sub-string is found

Question:

How would I find all instances of a sub-string in a list of strings and return the index of the string where the sub-string is found in Python?

For example:

sub_string = "tree"
my_list = ["banana", "tree", "trees", "street"]

The desired output would be: [1,2,3] as tree is found within the strings at the indices of 1, 2, 3.

I have this in the form of a function but it only returns the first instance of the sub-strings index and doesn’t recognize the sub-string in a string (tree in street for example).

def inside_search(a_list, search_term):
    if search_term in a_list:
        index = a_list.index(search_term, 0, -1)
        return [index]
    else:
        return []

cats_and_dogs_list = ["cat", "cats", "dog", "dogs", "catsup"]
print(inside_search(cats_and_dogs_list, "cat"))

My function returns [0] but I want it to return [0,1,4]

I have tried and solved this several ways using several methods but I can’t seem to return anything but [0].

Asked By: H20zzz

||

Answers:

Use list comprehension with enumerate:

>>> [i for i, w in enumerate(my_list) if sub_string in w]
[1, 2, 3]

If you want to use a function:

def inside_search(a_list, search_term):
    result = list()
    for i, word in enumerate(a_list):
        if search_term in word:
            result.append(i)
    return result

>>> inside_search(cats_and_dogs_list, "cat")
[0, 1, 4]
Answered By: not_speshal

This is what you’re looking for:

print([my_list.index(item) for item in my_list if sub_string in item])

Hope this helped 🙂 Cheers!

Thanks all, I struggled for a day with this one, eventually came up with this…

def inside_search(cats_and_dogs_list, searchitem):
for listitem in cats_and_dogs_list:
indices = []
if searchitem in listitem:
index = (cats_and_dogs_list.index(listitem))
indices.append(cats_and_dogs_list.index(listitem))
return(indices)

not right at all… so TY for the enumerate answer it has helped immensely

Answered By: Arion
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.