2

Given the list:

li = ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']

How do I find the (first) index containing the string amp? Note that amp is contained the word example.

FYI, this works: li.index("example")

But this does not: li.index("amp")

user2295350
  • 303
  • 4
  • 13
  • related: [Python: find first element in a sequence that matches a predicate](http://stackoverflow.com/q/8534256/4279) – jfs Aug 14 '13 at 09:19

1 Answers1

10

You can use a generator expression with next and enumerate:

>>> next((i for i,x in enumerate(li) if 'amp' in x), None)
5

This will return None if no such item was found.

TerryA
  • 58,805
  • 11
  • 114
  • 143
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504