The Iterator Pattern in Python
Explore the iterator pattern in Python to understand the distinction between iterable objects and iterators. This lesson helps you learn how to implement __iter__ and __next__ methods properly, use sequences for iteration, and design efficient, readable iterable objects. You will gain insights into Python's iteration mechanisms and improve your ability to write maintainable code.
We'll cover the following...
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, such as sequences and container objects.
The interface for iteration
An iterable is an object ...