In this post we will be creating a Python script that will create an iterator consisting of incremental numbers, to do this we will be using the Itertools module implements a number of iterator building blocks inspired by constructs from APL, Haskell, and SML.
See the sample of Python code that creates an incremental number iterator and prints the number to output. The example below will continue to print to infinity with no break present.
import itertools
for i in itertools.count():
print(i)
See the snippet of code that creates a similar iterator although here the starting number is set to ‘5’, our number will also increment by ‘2’ each time. Here the script will stop iterating once our number reaches 40.
import itertools
for i in itertools.count(5, 2):
print(i)
if i > 40:
break
The output of the above can be seen below.
5
7
9
11
13
15
17
19
21
23
25
27
29
31
33
35
37
39
41
>>>
Take a look at some of our other content around the Python programming language by clicking here.