Home > Blockchain >  How to find list index of a string containing a substring
How to find list index of a string containing a substring

Time:09-21

ar = ['hello there','everyone']

How do I find the index of the element containing the substring "hell"?

CodePudding user response:

Just use next with enumerate.

>>> next((i for i, v in enumerate(ar) if 'hell' in v), None)
0
>>> 

Or filter:

>>> next(filter(lambda x: 'hell' in x[1], enumerate(ar)), [None])[0]
0
>>> 

Or simply:

>>> ar.index(next(filter(lambda x: 'hell' in x, ar), None))
0
>>> 

And:

>>> ar.index(next((v for v in ar if 'hell' in v), None))
0
>>> 

Notice that all 4 solutions I added a None at the end (one case [None]). If you're sure that there will be matches in the list for sure, you could remove them.

  • Related