Iterators: brief words about them

Generally, we all iterate through a variety of objects in Python, like:

Tuples
Lists
Dictionaries
Strings
Sets

But besides theses objects, you can create your own iterable object! Cool huh?

Not that often you might run on this situation, but it's good to know how to build your own iterator and also, you will learn a bit more of Python internals and how the iteration works behind the curtains.

The __iter__ and __next__ methods

Data structure objects like the ones listed above, are all iterable objects. You can get an iterator for any of them, by using the iter() method, and then iterating over it with next() method. If all elements from the iterator were called, then a StopIteration exception will be thrown.

Your Iterator

Built as class, your iterator should have __iter__() and __next__() methods implemented: one for initializing your iterator object, and the other for providing the current iterator value, also calculating the next iteration:
The problem here is that, without a condition, this iteration can go forever:

Depending on your code, you might want to have a condition externally expressed, but most of the cases, the condition of how many interations will be supported by the iterator, are defined on the class which provides the iterator.


Max Number of Iterations

Just as any class, you can define the __init__() method for the iterator class, where you can define the limit of the iterator:


Final Words

Hope you had fun while reviewing this topic and hope that it might help you some day. I decided to write it here, for I went thtough some situation where implementing an iterator was necessary, and here's a record of something that I initially tried, in order to understand how to build one.

From now on, everytime that you iterate through an iterable object, you can have an idea of what's going on with this object, how the data is being processed, stored, and understand that, there might be very specific scenarios where you would like to implement your own iterator.

For more examples and resources, here's a cool document from Python official documentation.

Mastodon