Python Iterators

Iterators, this name might be new for most of us, but What if I tell you that you have already used this within for loops, comprehensions etc. So, in this blog, let’s see what are iterators, how they work and how we can build our own iterator.

What is an iterator and how it works?

To understand this, we first need to know what is an iterable

Iterable: It is anything that you are able to loop over like lists, tuples, strings etc.

Iterator: It is the object that does the actual iterating.

So, in order to iterate, you must first convert an iterable into an iterator. This is done by using built-in iter() function.

To get the next element, use built-in next() function on that iterator. next() function raises a StopIteration exception when there are no more elements in that iterator.

Note: If we directly apply next() on iterable like lists etc. it will give a typeerror as

Thus, __iter__() and __ next__() (called the iterator protocol)are the two special methods implemented by the iterator.

Pros:  Iterators are lazy, meaning, they don’t determine what their next item is until you ask them for it. This saves memory, time and can work with infinite sequences.

Building our own iterator:

To build an iterator, we only need the methods __iter__() and __next__(). Below, we show an example that will give us the next Fibonacci term in each iteration.

Now we can create an iterator and iterate through it as follows.

Here, I haven’t called the iter() method because it returns the object itself. You may call this, as this will not affect anything.

We can also use for loop to iterate over our Fib Class as:

Here, for loop doesn’t give stopiteration exception because it uses try-except statement(See here how the for loop works)

Now, you might have got some feeling about the Python iterators and iterable. Hope you enjoy reading.

If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.

Leave a Reply