Creating a Python iterator (Python 3 )

Creating a Python iterator

There’s no magic to creating your own iterator. I’ll demonstrate with a simple iterator class that returns even numbers.

As we’ve learned, we need to implement __iter__ and __next__. We’ll do this in one single class, to keep things simple. We accomplish this with an __iter__ method that simply returns self. We could make this an endless iterator. But for the sake of demonstration, we’ll raise a StopIteration exception as soon as we go past the number 8.

Remember that if you build an iterator this way, you can not use it in a concurrent environment. In such cases, you should return a new object on each call to iter.

To learn more, read the Python iterators tutorial at Python Land.

Edit and run this Python 3 example code

This code is editable and runnable. You can run "Creating a Python iterator" by pressing the run button. It will be executed in our backend and the result (stdout and stderr) is displayed in addition tabs.

Share "Creating a Python iterator"

Share this crumb (Creating a Python iterator) with your friends and colleagues to help them learn more about Python 3 programming.

Twitter, Facebook, LinkedIn

On Twitter, Facebook, and LinkedIn, simply paste the URL in your post and watch the magic unfold.


If you want to embed the crumb in an iframe, use the following code:

oEmbed (WordPress)

We support oEmbed, but most sites use allowlisting. On WordPress, oEmbed is supported out of the box, but see the note below.

If you plan to use heavily on Wordpress, you can use the following PHP code to allowlist our site and unlock all the functionalities of our crumbs:
wp_oembed_add_provider( '*', '' ); is a service that allows you to embed content from other sites. We will request to be added to the list of trusted sites once we're out of beta.