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 (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
0so that we start counting from
We set our
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:
0 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 we can display!
First, import the
itertools module at the top line of the code editor.
Next, initialize a
for loop with a
count() iterator that keeps track of the weight on the shelf.
for loop body:
- Provide a stop condition using
max_capacityto terminate the loop
num_bagson each iteration.
num_bags result to see how many bags will fit on the shelving unit.