Functional Python Programming

(Wang) #1

The Itertools Module


The itertools recipes


The itertools chapter of the Python library documentation, Itertools Recipes, is
outstanding. The basic definitions are followed by a series of recipes that are
extremely clear and helpful. Since there's no reason to reproduce these, we'll
reference them here. They should be considered as required reading on functional
programming in Python.


10.1.2 section, Itertools Recipes of Python Standard Library, is a
wonderful resource. See
https://docs.python.org/3/library/itertools.
html#itertools-recipes.

It's important to note that these aren't importable functions in the itertools
modules. A recipe needs to be read and understood and then, perhaps, copied or
modified before inclusion in an application.


The following table summarizes some of the recipes that show functional
programming algorithms built from the itertools basics:


Function Name Arguments Results
take (n, iterable) This returns the first n items of the iterable
as a list. This wraps a use of islice() in a
simple name.
tabulate (function,
start=0)

This returns function(0) and
function(1). This is based on a
map(function, count()).
consume (iterator, n) This advances the iterator n steps ahead. If n
is None, iterator consumes the steps entirely.
nth (iterable, n,
default=None)

This returns the nth item or a default value.
This wraps the use of islice() in a simple
name.
quantify (iterable,
pred=bool)

This counts how many times the predicate is
true. This uses sum() and map(), and relies
on the way a Boolean predicate is effectively 1
when converted to an integer value.
padnone (iterable) This returns the sequence elements and then
returns None indefinitely. This can create
functions that behave like zip_longest()
or map().
ncycles (iterable, n) This returns the sequence elements n times.
Free download pdf