Functional Python Programming

(Wang) #1

The Itertools Module


We need to emphasize an important limitation of iterables that we've touched upon
in other places.


Iterables can be used only once.
This can be astonishing because there's no error. Once exhausted,
they appear to have no elements and will raise the StopIteration
exception every time they're used.

There are some other features of iterators that aren't such profound limitations.
They are as follows:



  • There's no len() function for an iterable. In almost every other respect, they
    appear to be a container.

  • Iterables can do next() operations, unlike a container.

  • The for statement makes the distinction between containers and iterables
    invisible; containers will produce an iterable via the iter() function.
    An iterable simply returns itself.


These points will provide some necessary background for this chapter. The idea
of the itertools module is to leverage what iterables can do to create succinct,
expressive applications without the complex-looking overheads associated with the
details of managing the iterables.


Working with the infinite iterators


The itertools module provides a number of functions that we can use to enhance
or enrich an iterable source of data. We'll look at the following three functions:



  • count(): This is an unlimited version of the range() function

  • cycle(): This will reiterate a cycle of values

  • repeat(): This can repeat a single value an indefinite number of times


Our goal is to understand how these various iterator functions can be used in
generator expressions and with generator functions.


Counting with count()


The built-in range() function is defined by an upper limit: the lower limit and
step values are optional. The count() function, on the other hand, has a start and
optional step, but no upper limit.

Free download pdf