24

How to obtain the index of the current item of a Python iterator in a loop?

For example when using regular expression finditer function which returns an iterator, how you can access the index of the iterator in a loop.

for item in re.finditer(pattern, text):
    # How to obtain the index of the "item"
Cœur
  • 32,421
  • 21
  • 173
  • 232
bman
  • 3,698
  • 3
  • 31
  • 63

1 Answers1

34

Iterators were not designed to be indexed (remember that they produce their items lazily).

Instead, you can use enumerate to number the items as they are produced:

for index, match in enumerate(it):

Below is a demonstration:

>>> it = (x for x in range(10, 20))
>>> for index, item in enumerate(it):
...     print(index, item)
...
0 10
1 11
2 12
3 13
4 14
5 15
6 16
7 17
8 18
9 19
>>>

Note that you can also specify a number to start the counting at:

>>> it = (x for x in range(10, 20))
>>> for index, item in enumerate(it, 1):  # Start counting at 1 instead of 0
...     print(index, item)
...
1 10
2 11
3 12
4 13
5 14
6 15
7 16
8 17
9 18
10 19
>>>