101
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

5 Answers 5

167

You can use enumerate inside a list-comprehension:

indices = [i for i, s in enumerate(mylist) if 'aa' in s]
7
  • how can you make this be case insensitive?
    – abbood
    Commented Feb 14, 2017 at 6:45
  • 1
    @abbood - By comparing to s.lower() Commented Feb 14, 2017 at 11:22
  • what if I just want to get single index for the first match only?
    – shashwat
    Commented Oct 6, 2017 at 15:48
  • @shashwat - You don't have to use the generator expression in the brackets to created a list. You can use it to create a generator gen = () which you then call next on. Commented Oct 6, 2017 at 18:25
  • if you could please give an example for how I use this? I am completely new to Python.
    – shashwat
    Commented Oct 7, 2017 at 5:24
24

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]
2
  • How might the list comprehension get extended to instead of "if 'aa'" to be "if ["aa","bb"] in elem" ?? Commented Apr 17, 2018 at 12:46
  • @GrantRWHumphries You go one level lower with second for loop: indices = [i for i, elem in enumerate(mylist) if any(a in elem for a in ["aa","bb"])].
    – Daniel
    Commented Jan 29, 2022 at 13:33
12

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]
2
  • 12
    This is likely to run in O(n^2), whereas using enumerate will be O(n).
    – johnsyweb
    Commented Feb 13, 2013 at 8:33
  • 6
    This will return a wrong result if one of the strings containing 'aa' is duplicated. Commented Feb 13, 2013 at 10:01
2

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.

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

index=spell_list.index("Annual")
print(index)
2
  • 1
    This does not answer the question. A value error will be thrown when you use this method but only specifies list.index('an'). The method will be unable to find annual.
    – mastersom
    Commented Nov 26, 2019 at 11:37
  • 1
    Right. This is an incorrect answer to the question that has been asked.
    – Ombrophile
    Commented May 19, 2020 at 13:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.