In this article we will discuss the differences between Iterators and Generators in Python.

Iterators and Generators both serves similar purpose i.e. both provides the provision to iterate over a collection of elements one by one. But still both are different. Let’s discuss how they are different

Ease of implementation

Making your class Iterable and the creating Iterator class to iterate over the contents of Iterable requires some extra coding.
Let’s understand by an example,

Suppose we have a simple Range class i.e.

Now we want to iterate over the numbers in this range using the object of our MyRange class i.e.

It will show error like this,

It returns the error because our MyRange class is not Iterable. Now we need to make our class Iterable and create an Iterator class for it i.e.

Iterator class,

Now we can iterate over the numbers in range using MyRange class object i.e.

Output

Basically we override __iter__() function in our MyRange class to make it Iterable and the overridden __next__() function in MyRangeIteration class to make it an Iterator.

We can avoid this extra class if use Generator i.e.

Creating Range class with Generator

Instead of making our range class Iterable we can add a generator function in the class that returns a Generator object. This Generator object can be used to iterate over the numbers in range,

Now let’s iterate over the numbers in range using MySecondRange class object i.e.

Output:

So, basically Generators servers the same purpose as Iterators but in less code.

Multiple Generators but Single Iterator

There can be a single Iterator associated with a Iterable class. For example in our Iterable class MyRange, we returned the MyRangeIterator object that iterates the numbers in range from start to end. What if we want to Iterate in reverse or in some other order ?

We can not do that using Iterators because Iterable class returns a single type of Iterator object. But we can do that using Generators.
For example, let’s add two generator functions in our MySecondRange class i.e.

 

Now using Generator object returned by forwardTraversal(), we can iterate over the numbers in range in forward direction i.e.

Output:

 

Whereas, using Generator object returned by reverseTraversal(), we can iterate over the numbers in range in backward direction i.e.

Output:

So, unlike Iterator, with Generators we can iterate over the elements in multiple ways.

Complete example is as follows.

Output:

 

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Do Subscribe with us for more Articles / Tutorials like this,