Python Generators vs Iterators
Iterators and generators have similar functionality, which might be confusing at times. This article compares iterators and generators in order to grasp the differences and clarify the ambiguity so that we can choose the right approach based on the circumstance.
Iterators in Python
Python objects that iterate through iterable objects are called Iterators. It is used to iterate over objects by returning one value at a time. Iterators are created by using the iter() function. The function next() is used to get the subsequent value from the iterator.
Example of Iterators in Python
nums = [1, 2, 3, 4] obj = iter(nums) print(next(obj)) print(next(obj)) print(next(obj)) print(next(obj))
Output
2
3
4
Generators in Python
A generator is a type of function that returns a generator object, which can return a sequence of values instead of a single result. The def keyword is commonly used to define generators. At least one yield statement is required in a generator.
Example of Generators in Python
def nums(): for i in range(1, 5): yield i obj = nums() print(next(obj)) print(next(obj)) print(next(obj)) print(next(obj))
Output
2
3
4
Comparison Between Python Generators and Iterators
Implementation of Generators and Iterators
Iterators are created using classes whereas generators are created using functions.
Example of Iterators in Python
class Alphabets: def __iter__(self): self.val = 65 return self def __next__(self): if self.val > 90: raise StopIteration temp = self.val self.val += 1 return chr(temp) my_letters = Alphabets() my_iterator = iter(my_letters) for letter in my_iterator: print(letter, end = " ")
Output
Example of Generators in Python
def Alphabets(): for i in range(65, 91): yield chr(i) my_letters = Alphabets() for letter in my_letters: print(letter, end=" ")
Output
By looking at the above two code examples, we can understand that it is much easier to create generators than iterators
We can also notice that generators require a yield statement whereas iterators don’t.
Use of Local Variables by Generators and Iterators in python
Iterators don’t use any variables to iterate whereas generators use local variables and store the state of those variables whenever the loop is paused by the yield statement.
Example of Iterators in Python
li = ["A", "B", "C", "D"] li_iter = iter(li) print(next(li_iter)) print(next(li_iter)) print(next(li_iter))
Output
B
C
Example of Generators in Python
def gener(): num = 1 while True: yield num num += 1 obj = gener() print(next(obj)) print(next(obj)) print(next(obj))
Output
2
3
Generators are Iterators in Python
In Python, all generators are iterators. This can be proved by the fact that generators are a subclass of iterators.
Example of issubclass() in Python
from collections.abc import Generator, Iterator print(issubclass(Generator, Iterator))
Output
In the above code example, we can see that generator is a subclass of iterator and the iterator is a subclass of iterable.
Use-Cases of Generators and Iterators in python
Iterators are mostly used to convert iterables and iterate such iterables but generators are mostly used to create iterators and generate new values in a loop without disturbing the iteration of that loop.
Summary of Differences between Generators vs Iterators in Python
Iterators in Python | Generators in Python |
Implemented using Class | Implemented using Function |
No yield statement | Use yield statement |
Use the iter() function | Do not use the iter() function. |
Local variables are not used | Local variables are used |
They are mostly used to convert iterables into iterators | They are mostly used to create iterators |
All iterators are not generators | All generators are iterators |
Python Interview Questions on Generators vs Iterators
Q1. Print the first three elements of a list using the iter() function.
Ans 1.
Complete code is as follows:
List = ["orange", "green", "black"] list_iter = iter(List) print(next(list_iter)) print(next(list_iter)) print(next(list_iter))
Output
green
black
Q2. Print the first three elements of a list using a generator.
Ans 2. Complete code is as follows:
def gener(): List = ["orange", "green", "black"] for item in List: yield item iter_obj = gener() print(next(iter_obj)) print(next(iter_obj)) print(next(iter_obj))
Output
green
black
Q3. Create an iterator that prints the first four lower case alphabets.
Ans 3. Complete code is as follows:
def abcd(): for i in range(97, 101): yield chr(i) obj = abcd() print(next(obj)) print(next(obj)) print(next(obj)) print(next(obj))
Output
b
c
d
Q4. Create an iterator using a class that prints the multiples of 5 infinitely.
Ans 4. Complete code is as follows:
class Multiples: def __iter__(self): self.val = 1 return self def __next__(self): temp = self.val self.val += 1 return temp*5 multiples5 = Multiples() obj = iter(multiples5) print(next(obj)) print(next(obj)) print(next(obj))
Output
10
15
Q5. Create an iterator using a function that prints the multiples of 5 infinitely.
Ans 5. Complete code is as follows:
def Multiples(): i = 1 while True: yield i*5 i += 1 multiples5 = Multiples() obj = multiples5 print(next(obj)) print(next(obj)) print(next(obj))
Output
10
15
Conclusion
In this article, we learned about the differences between iterators and generators. This helps us in choosing the best method to maximize the efficiency of our program. Furthermore, if you have any queries, please express them in the comments section.
The best description of a difference between iterator and generator I’ve seen so far, graet job!
great examples here, kudos!!!
IM still having some trouble. My issue is the use of the temp variable and the use of classes for iterators (Is that just for iterators we create ourselves?). In the iterator part of the use of temp variable section, the iterator uses a temp variable. What is the difference between that example and using the class attribute as a tempp variable? I’m having trouble just articulating it, i apologize I’m just gonna sum up what i think of each and if anyone can point where my lapse of understanding is it would be appreciated.
Generators are made with functions and use the yield keyword. Every time the yield is hit the state of the object is assigned to a temporary variable. Use case ex: for num in range(10)
Iterators are objects that are able to iterate through other objects returning one value for each next() called (this is where i intuitively think a temp variable is used but it explicitly says it does not). Objects can be transformed into iterables with inter().
Use case ex:
s = ‘hello’
s = iter(s)
next(s)
next(s)
next(s)
and so on.
Thank you for any feedback I’ve been struggling through python for quite awhile and I know it stems from this lack of fundamental knowledge.