Generators and Iterator objects


In the last session we had an introduction about generators, today we will see difference between generators and the iterator object in this Generators and iterator objects tutorial.

  • An iterator is an object which is used to traverse a container like lists.
  • Iterators are often provided by the containers interface.
  • An iterator traverses throughout the container and also gives access to the data in it.
  • But implementing iterator is very complex and time consuming.
  • Whereas generators with its generator function and yield keyword has made this task very simple and economic in time.
  • Generators are forward only but iterators can traverse through both the sides.
  • The code written for generators is basically very less as compared to iterators.
  • Come on let us see an example code to compare both iterators and generators.
  • For this, create a new folder named generator_iterator in the htdocs folder in xampp folder. Open a new notepad++ document and save it as index.php in this newly created generator_iterator folder.
  • First we will write code for iterator in index.php file:
  • Now the code for same task using generators is as follows:
  • Here you can see that a lot of code is needed to implement an iterator with a lot of complexity.
  • We know that some built-in classes have provided iterators; but if we are designing our own class to deal with a large data and it doesn’t matter if the data is not stored, we can use generators.
  • Because iterators need a lot of memory and take a long time to work.
  • Generators provide the desired value immediately and works faster.
  • But generators are forward only; they cannot be rewound to again repeat the values. To allow it to do this, it need to be called again or it can be cloned using clone keyword.

Thus we see that as the generator object maintains its state and generate a new value on each iteration with less use of memory, it is very economic to use in the suitable conditions although not useful in day to day tasks.


Please enter your comment!
Please enter your name here