Implementing Iteration

Agenda

  1. Review: Iteration
  2. Details: iterables, iterators, iter, and next
  3. Implementing iterators with classes
  4. Implementing iterators with generators and yield

1. Review: Iteration

Iteration simply refers to the process of accessing — one by one — the items stored in some container. The order of the items, and whether or not the iteration is comprehensive, depends on the container.

In Python, we typically perform iteration using the for loop.

2. Details: iterables, iterators, iter, and next

We can iterate over anything that is iterable. Intuitively, if something can be used as the source of items in a for loop, it is iterable.

But how does a for loop really work?

3. Implementing iterators with classes

For a container type, we need to implement an __iter__ method that returns an iterator.

4. Implementing iterators with generators and yield

What's a "generator"?