Now, we will introduce a couple of iterator tools that often come in very handy:
- enumerate is used to enumerate another iterator. It produces a new iterator that yields pairs (iteration, element), where iteration stores the index of the iteration:
A = ['a', 'b', 'c'] for iteration, x in enumerate(A): print(iteration, x) # result: (0, 'a') (1, 'b') (2, 'c')
- reversed creates an iterator from a list by going through that list backward. Notice that this is different from creating a reversed list:
A = [0, 1, 2] for elt in reversed(A): print(elt) # result: 2 1 0
- itertools.count is a possibly infinite iterator of integers:
for iteration in itertools.count(): if iteration > 100: break # without this, the loop goes on forever print(f'integer: {iteration}') # prints the 100 first integer
- intertools.islice truncates...