Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Iterators and Generators

Open in Colab

So far, we have used for loops over lists like

This looks very different from a C-style for loop where we loop over the variable index:

for (size_t i = 0; i < 3; i++) {
    printf("%d\n", i);
}

Or for instance, we can use something called a range

or other data types

The key to using this sort of syntax is the concept of iterator. This is common in object-oriented programming (not just in Python), but you probably haven’t seen iterators before if you’ve only used imperative languages.

An object is iterable if it implements the __iter__ method, which is expected to return an iterator object. An object is an iterator if it implements the __next__ method, which either

  1. returns the next element of the iterable object

  2. raises the StopIteration exception if there are no more elements to iterate over

Informally, an iterable is something you can loop over, like a list, a string, or a range. An iterator is the object that remembers how far the loop has gotten and hands out the elements one at a time. The built-in functions iter(x) and next(it) call x.__iter__() and it.__next__() for us.

A Basic Iterator

What if we want to replicate range?

we can produce an iterator using the iter function

we can explicitly run through the iterator using the next function

Each call to next moves the iterator forward by one element. range(1, 5, 2) only contains 1 and 3, so a third call has nothing left to return, and next raises a StopIteration exception instead:

This is how a for loop knows when to stop. A loop like for x in a: first calls iter(a) to get an iterator, then calls next on that iterator over and over until it raises StopIteration. Written out by hand, the loop from the top of this page is roughly

An iterator only moves forward, and once it is exhausted it stays exhausted. The iterable is not used up, though. Every call to iter creates a new iterator that starts from the beginning, which is why we can loop over the same list or range as many times as we want.

To replicate range, we write two classes. my_range is the iterable: it stores start, stop, and stride, and its __iter__ method creates a new iterator.

my_range_iterator is the iterator: it stores the current position in self.state, and each call to __next__ returns the current value and then moves state forward by stride. Once state reaches stop, it raises StopIteration.

You can also create classes that are both iterators and iterables

Because __iter__ returns self, a my_range2 object is its own iterator. Python’s built-in iterators work the same way: calling iter on an iterator gives back the iterator itself, which is why a for loop accepts an iterator as well as an iterable.

The catch is that the position state is now stored on the my_range2 object itself, so it can only be looped over once. my_range doesn’t have this problem, since every loop gets a fresh my_range_iterator:

Using Iterators for Computation

Let’s now use iterators for something more interesting - computing the Fibonacci numbers.

Note that we never raise a StopIteration exception - the iterator will just keep going if we let it.

A list could never do this. The Fibonacci sequence is infinite, so there is no way to store all of it, but the iterator doesn’t have to: it only computes the next number when the loop asks for one. This is called lazy evaluation. In the loop above, the break is what stops the iteration. Be careful with infinite iterators: something like list(FibonacciIterator()) never finishes.

Exercise

Define FibonacciIterator so it will iterate over all Fibonacci numbers until they are greater than a parameter n.

Generators

Often, a more elegant way to define an iterator is using a generator

This is a special kind of iterator defined using a function instead of using classes that implement the __iter__ and __next__ methods.

See this post for more discussion.

Note that we use the def keyword instead of the class keyword for our declaration. The yield keyword returns subsequent values of the iteration.

iter(r) returned r itself (you can check that ri is r). A generator is its own iterator, like my_range2, so it can only be looped over once.

How yield works

A generator function doesn’t run like a normal function. Calling my_range3(0, 3) doesn’t run any of the code in its body; it only creates a generator object. Each call to next then runs the body until it reaches a yield. next returns the yielded value, and the function pauses right there, keeping its local variables. The following call to next resumes right after the yield. When the function returns (at a return statement or by reaching the end of its body), the generator raises StopIteration.

So my_range3 does the same job as the my_range2 class with much less code: Python writes the __iter__ and __next__ methods for us, and the local variables state, stop, and stride take the place of the attributes on self.

Adding some print statements shows the order in which things happen:

Our Fibonacci example re-written using a generator. The attributes self.a and self.b of FibonacciIterator become local variables, which the generator keeps between calls to next:

Exercise

Define FibonacciGenerator so it will iterate over all Fibonacci numbers until they are greater than a parameter n.

Generator expressions

For short generators there is a shorthand that looks like a list comprehension with parentheses instead of square brackets. A list comprehension computes every element right away and stores them all in a list. A generator expression creates a generator, which computes the elements one at a time as they are asked for.

A generator only stores its current state, so its size doesn’t depend on how many values it will produce. If you only need to go through the values once, for example to add them up, a generator expression saves you from building the whole list first.

Iteration tools

Some useful tools for iterators that come in handy are zip, reversed, and enumerate. Each of them returns an iterator, so like a generator, it produces its values lazily instead of building a list.

zip - iterates over multiple iterators simultaneously, stopping as soon as the shortest one runs out

reversed - iterates in reverse order. It has to start from the last element, so it works on sequences like lists, strings, and ranges, but not on generators, which can only move forward.

enumerate - returns the iteration step count as well as the iterator value

Exercise

Implement your own versions of zip and enumerate using generators

Notebook Cell
Notebook Cell

The Itertools Package

A useful package for dealing with iterators is the itertools package. Here are a few examples - click on the link to see what else the package provides.

product gives the equivalent of a nested for-loop

repeat just repeats a value

permutations

Exercise

Implement your own version of product and repeat using generators.

Notebook Cell
Notebook Cell

Iterators for Scientific Computing

One way you might use an iterator in scientific computing is when implementing an iterative algorithm.

Here is an example of gradient descent:

xk+1=xk−α∇f(xk),x_{k+1} = x_k - \alpha \nabla f(x_k),

with a fixed step size α\alpha. The gradient is zero at a minimum, so we stop once ∥∇f(xk)∥\|\nabla f(x_k)\| is small.

Writing the algorithm as a generator splits the work into two parts. The generator only knows how to take one step of the iteration, and it yields the current state after each step. The code that uses the generator decides what to do with each iterate and when to stop.

As a test problem, we minimize the quadratic

f(x)=12x⊤Ax−b⊤xf(x) = \frac12 x^\top A x - b^\top x

for a random 100×100100 \times 100 symmetric positive definite matrix AA. Its gradient is ∇f(x)=Ax−b\nabla f(x) = Ax - b, so the minimizer is the solution of Ax=bAx = b, which lets us check the answer at the end. The eigenvalues of this AA lie between 1 and about 5, and gradient descent converges as long as α<2/λmax⁡≈0.4\alpha < 2 / \lambda_{\max} \approx 0.4.

If we decide that we’re not satisfied with convergence yet, we can resume where we left off. The generator is paused at its yield with the current x still stored in its local variables, so calling next again continues the iteration instead of starting over from x=0x = 0.

The result agrees with the solution of Ax=bAx = b computed by np.linalg.solve:

You can do the same thing with for-loops. Breaking out of the first loop leaves the generator paused, not finished. The second loop calls iter(solver), which returns the same generator, so it picks up where the first loop stopped.

This time we use enumerate to count the steps instead of printing every iterate. A new enumerate starts counting from 0, so the second loop passes start=k + 1 to continue the count.