top of page
Search
  • Writer's pictureMaia

Python Tips Series: Iterator


Iterators are everywhere in Python. They are elegantly implemented within for loops, comprehensions, generators etc, but they are hidden in plain sight.

Iterators are objects that can be iterated upon. In this post, we will learn how iterator works and how we can build your own iterator using __iter__ and __next__ methods.

Let's take a look at the iter() function and the __iter__() method first.

We can use iter() function on any List or Iterable object to get an Iterator object. Then, we can call the next() function on the Iterator object to get the next element.

But when we reach to the end of the Iterator object, if we continue to call next() function we will get an error.

We normally using for loop in our code to iterate through Iterable object like List, we rarely use Iterator object directly. However, under the hood the for loop itself actually using the Iterator object to do that for us.

In Python, that is called Iterator protocol so that any object can make itself becomes iterable so that it can be iterated through in for loop.

We can create our own class that implements this Iterator protocol.

This implementation has one problem below.

To overcome this problem, we implement it as below.

Now our class can be looped many times.

That's how Iterator and Iterable work in Python.


Happy Iterating!



Recent Posts

See All

Comments


Post: Blog2_Post
bottom of page