0

So I have a following list:

found = ['ITERATION 0', 'string', 'ITERATION 1', 'string', 'ITERATION 2', 'string']

I am trying, and I can't for the life of me find any answers from StackOverflow or Youtube, to extract the index of each ITERATION.

So in my example the reslt would be [0, 2, 4].

I can use found.index(r'ITERATION 0') to find the specific occurrence; but this doesn't help me find 2 and 4.

martineau
  • 119,623
  • 25
  • 170
  • 301
Jay P
  • 1
  • 1
    http://stackoverflow.com/questions/176918/finding-the-index-of-an-item-given-a-list-containing-it-in-python – snagpaul Nov 12 '16 at 04:25
  • 1
    Sometimes you have to figure out the answer yourself rather than searching for something canned. – martineau Nov 12 '16 at 05:54

1 Answers1

2

You can use enumerate with list comprehension:

>>> found = ['ITERATION 0', 'string', 'ITERATION 1', 'string', 'ITERATION 2', 'string']
>>> [i for i, s in enumerate(found) if s.startswith('ITERATION')]
[0, 2, 4]

In above enumerate returns (index, string) tuples. For every tuple list comprehension checks if string starts with 'ITERATION' and if it does includes the index to the result.

niemmi
  • 17,113
  • 7
  • 35
  • 42