Iteration

What is iteration? Doing the same thing repeatedly, generally with a different, but related, piece of data. Programmers use iteration all the time, often even the ones who are using recursion.

Every time you are using for to process items in a list, you're using iteration. Every time you use a list comprehension, you're using iteration.

It's so common that Python has some builtin constructs to make it easier: iterators, iterables, and generators. These were covered in another guide.  As glimpsed in that guide, Python has a module that provides a wealth of tools for working with these: itertools.

In that guide we briefly looked at the small subset of itertools that has been ported to MicroPython.

This guide describes a fuller port that has been done to CircuitPython. Additionally, the itertools recipes functions have been largely made available as well.

Two modules are available as helpers in the CircuitPython Bundle:

adafruit_itertools - a port of the majority of Python's itertools functions.

adafruit_itertools_extras - a port of many of the itertools recipes functions. These are very useful function that are built on top of the core itertools module.

Why itertools?

Similar to how the math module provides functions that operate on numbers, itertools gives you functions that operate on iterators. This lets you code in a more functional* or dataflow-centric way, also sometimes known as stream-based programming..

The Python3/CPython version is implemented in C. The CircuitPython implementation is a pure Python implementation so it's performance isn't nearly as good, but should be adequate in most, if not all, situations. It has the additional benefit of being readily studied and understood.

One of the major advantage of using iterators is that they can be used to compute one value at a time rather than all the values at once. This has several implications:

  1. Computing time is spread out as required rather than all at once to populate (for example) a list of values.
  2. Since elements are computed as needed, memory to store the entire list is not required. This means you can process more data with less memory. This is very handle in a memory-limited environment.
  3. Since time and space is only required for one element at a time, we can deal with sequences of any length, even infinite, without any additional requirements.

*Functional as in functional programming, not as in it works.

Header image icon made by Designerz Base from www.flaticon.com

This guide was first published on Mar 25, 2019. It was last updated on Mar 08, 2024.

This page (Overview) was last updated on Mar 08, 2024.

Text editor powered by tinymce.