An infinite iterator will repeat an infinite number of times with no endpoint and no
StopIteration exception raised. Infinite iterators are useful when we have unbounded streams of data to process.
A useful itertool that is an infinite iterator is the
count() itertool. This infinite iterator will count from a first value until we provide some type of stop condition. The base syntax of the function looks like this:
The first argument of
count() is the value where we start counting from. The second argument is an optional step that will return
current value + step. The step value can be positive, negative, and an integer or float number. It will always default to 1 if not provided.
To show how it’s used in a scenario, suppose we want to quickly count up and print all even numbers from 0 to 20.
We first import our itertools module and then create a loop of some sort (this can be a
while loop or a
for loop), that will iterate through our
import itertools for i in itertools.count(start=0, step=2): print(i) if i >= 20: break
Here is what happens in the script:
We set our start argument to
0so that we start counting from
We set our step argument to
2so that way we increment +2 on each iteration.
We create a stop condition, which is
i >= 20, otherwise this
forloop would continue printing forever!
And our output becomes:
2 4 6 8 10 12 14 16 18 20
Let’s use the
count() itertool to manage our pet store!
We have several 13.5lb bags of dog food to display. Our single shelving unit however can only hold a maximum of 1,000lbs. Let’s figure out how many bags of food can we display!
First, import the
itertools module at the top line of the code editor.
Next, initialize a
for loop to create the
count() iterator with appropriate start and step values.
for loop body, provide a stop condition using
max_capacity to terminate the loop and increment
num_bags on each iteration.
num_bags result to see how many bags will fit on the shelving unit.