Using the itertools module
Beyond just the standard iteration protocol, Python also provides the itertools
module. This module provides a number of iterator building blocks that, used singly or in combination, can create specialized iteration tools for efficient looping.
How to do it...
There are three main categories of itertools
: infinite iterators, combinatoric iterators, and iterators that terminate on the shortest input sequence.
Infinite iterators
Infinite iterators return values repeatedly until a terminating condition is reached:
TheÂ
count(start=0, step=1)
 function returns evenly spaced values that start at thestart
argument provided. Stepping is provided to allow skipping values. This function is frequently used withmap()
to generate consecutive data points. When used withzip()
, it can be used to add sequence numbers:
- In this example, we import the
count()
function from theitertools
module in line 54. - In line 55, we create a counting loop, starting with the integer
5
and a stepping...
- In this example, we import the