Let's discuss iterators and their types.

Python provides a great module for creating our own iterators. The module we are referring to is itertools. The tools provided by itertools are fast and memory efficient. We will use these building blocks to create our own specialized iterators that can be used for efficient looping. In this chapter, we will be looking at examples of each building block so that by the end we will understand how to use them for our own code bases.

Let’s get started by looking at some infinite iterators!

The infinite iterators

The itertools package comes with three iterators that can iterate infinitely. What this means is that when we use them, you need to understand that we will need to break out of these iterators eventually or we’ll have an infinite loop.

These can be useful for generating numbers or cycling over iterables of unknown length. Let’s get started learning about these interesting iterables!

count(start=0, step=1)

The count iterator will return evenly spaced values starting with the number we pass in as its start parameter. count also accepts a step parameter. Let’s take a look at a simple example:

Get hands-on with 1200+ tech skills courses.