...

/

The Iterator Pattern in Python

The Iterator Pattern in Python

Learn about the interface for iteration, as well as utilizing sequence objects as iterators.

Here, we will take a small detour from generators to understand iteration in Python more deeply. Generators are a particular case of iterable objects, but iteration in Python goes beyond generators, and being able to create good iterable objects will give us the chance to create more efficient, compact, and readable code.

In the previous code listings, we have seen examples of iterable objects that are also iterators because they implement both the __iter__() and __next__() magic methods. While this is fine in general, it's not strictly required that they always have to implement both methods, and here we'll show the subtle differences between an iterable object (one that implements __iter__) and an iterator (that implements __next__).

We also explore other topics related to iterations, ...