Question

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

Was it helpful?

Solution

You can use enumerate inside a list-comprehension:

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

OTHER TIPS

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]

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]
spell_list = ["Tuesday", "Wednesday", "February", "November", "Annual", "Calendar", "Solstice"]

index=spell_list.index("Annual")
print(index)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top