Creating Your Own Iterator

Learn to build your own iterator in this lesson.

We'll cover the following

Just out of interest, we will create a couple of iterators of our own. In fact, you will probably never need to do this, as it is almost always better to use generators instead, so the rest of the chapter is pretty much optional and for background information only.

This section assumes you know the basics of creating Python classes.

An iterator is just a class that implements a __next__ method and an __iter__ method. Notice that these functions have double underscores before and after their names, which indicates they are special class methods defined by Python. The built-in next function calls the object’s __next__ method (similar for iter).

As we noted earlier, the __iter__ method just needs to return the iterator itself (it allows the iterator to act as an iterable if needed). So, we will mainly concentrate on the __next__ method.

Get hands-on with 1200+ tech skills courses.