Find all index position in list based on partial string inside item in list

PythonListSubstringEnumerate

Python Problem Overview


mylist = ["aa123", "bb2322", "aa354", "cc332", "ab334", "333aa"]

I need the index position of all items that contain 'aa'. I'm having trouble combining enumerate() with partial string matching. I'm not even sure if I should be using enumerate.

I just need to return the index positions: 0,2,5

Python Solutions


Solution 1 - Python

You can use enumerate inside a list-comprehension:

indices = [i for i, s in enumerate(mylist) if 'aa' in s]

Solution 2 - Python

Your idea to use enumerate() was correct.

indices = []
for i, elem in enumerate(mylist):
    if 'aa' in elem:
        indices.append(i)

Alternatively, as a list comprehension:

indices = [i for i, elem in enumerate(mylist) if 'aa' in elem]

Solution 3 - Python

Without enumerate():

>>> mylist = ["aa123", "bb2322", "aa354", "cc332", "ab334", "333aa"]
>>> l = [mylist.index(i) for i in mylist if 'aa' in i]
>>> l
[0, 2, 5]

Solution 4 - Python

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.

Solution 5 - Python

spell_list = ["Tuesday", "Wednesday", "February", "November", "Annual", "Calendar", "Solstice"]

index=spell_list.index("Annual")
print(index)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionL ShawView Question on Stackoverflow
Solution 1 - PythonStoryTeller - Unslander MonicaView Answer on Stackoverflow
Solution 2 - PythonpemistahlView Answer on Stackoverflow
Solution 3 - PythonTerryAView Answer on Stackoverflow
Solution 4 - PythonJE_MucView Answer on Stackoverflow
Solution 5 - Pythonuser11167492View Answer on Stackoverflow