0 votes
1 view
in Python by (47.8k points)

What is the difference between iterators and generators? Some examples for when you would use each case would be helpful.

1 Answer

0 votes
by (107k points)

In Python iterator is a more general concept where an object whose class has a next method (__next__ in Python 3) and an __iter__ method that returns self.

Whereas, every generator is an iterator, but not vice versa. So defining a generator, Generators are built by calling a function that has one or more yield expressions (yield statements, It is only in Python 2.5 and its earlier versions), and is an object that meets the previous paragraph's definition of an iterator.

Below is an example for a generator:

def squares(start, stop):

     for i in range(start, stop):

            yield i * i

generator = squares(a, b)

We can write its equivalent generator expression (genexp) which is as follows:-

generator = (i*i for i in range(a, b))

Related questions

0 votes
1 answer
asked Sep 25, 2019 in Python by Sammy (47.8k points)
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !