Python Generators vs Iterators – Comparison Between Python Iterators and Generators

Free Python courses with 57 real-time projects - Learn Python

1. Generators vs Iterators

It’s been more than a month we began our journey with Python Programming Language. Through the days, we have also learned concepts like Python generators and iterators in Python. We know their functionalities. But how are they different? In this lesson, we discuss the comparison of python generator vs iterator. Before we proceed, let’s discuss Python Syntax.

python generator vs Iterator

Difference Between Python Generator vs Iterator

2. Introduction to Python Generators

A python generator function lends us a sequence of values to python iterate on. The following is an example of generators in python.

>>> def even(x):
       while(x!=0):
           if x%2==0:
                 yield x
              x-=1
>>> for i in even(8):
               print(i)

8
6
4
2
To see the generator in detail, refer to our article on Python Generator.

3. Introduction to Python Iterators

A Python iterator returns us an iterator object- one value at a time. Let’s take an example of an iterator in python.

>>> iter_obj=iter([3,4,5])
>>> next(iter_obj)

3

>>> next(iter_obj)

4

>>> next(iter_obj)

5

>>> next(iter_obj)

Traceback (most recent call last):

File “<pyshell#560>”, line 1, in <module>

next(iter_obj)

StopIteration

For more insight, check our Python Iterator tutorial.

4. Comparison Between Python Generator vs Iterator

Let’s see the difference between Iterators and Generators in python.

  1. In creating a python generator, we use a function. But in creating an iterator in python, we use the iter() and next() functions.
  2. A generator in python makes use of the ‘yield’ keyword. A python iterator doesn’t.
  3. Python generator saves the states of the local variables every time ‘yield’ pauses the loop in python. An iterator does not make use of local variables, all it needs is iterable to iterate on.
  4. A generator may have any number of ‘yield’ statements.
  5. You can implement your own iterator using a python class; a generator does not need a class in python.
  6. To write a python generator, you can either use a Python function or a comprehension. But for an iterator, you must use the iter() and next() functions.
  7. Generator in python let us write fast and compact code. This is an advantage over Python iterators. They are also simpler to code than do custom iterator.
  8. Python iterator is more memory-efficient. Lest see this with example below:
>>> def func():
       i=1
       while i>0:
                 yield i
                 i-=1
>>> for i in func():
             print(i)

1

>>> func().__sizeof__()

32
Here, we got 32. But for a python iterator, we get 16.

>>> iter([1,2]).__sizeof__()

16

  1. A generator returns a generator. Below an s example to understand it.
>>> f=func()
>>> type(f)

<class ‘generator’>
However, an iterator returns an iterator object.

>>> i=iter({1,3,2})
>>> type(i)

<class ‘set_iterator’>

  1. python Generator provides even more functionality as co-routines.

5. Relationship Between Python Generators and Iterators

a. A python generator is an iterator
Generator in python is a subclass of Iterator. To prove this, we use the issubclass() function.

>>> import collections,types
>>> issubclass(types.GeneratorType,collections.Iterator)

True

>>> issubclass(collections.Generator,collections.Iterator)

True

 >>> issubclass(collections.Iterator,types.GeneratorType)

False
b. Python iterator is an iterable
Iterator in python is a subclass of Iterable.

>>> issubclass(collections.Iterator,collections.Iterable)

True

6. Conclusion

Hence, we study the difference between python generator vs iterator and we can say every generator is an iterator in Python, not every python iterator is a generator. Both come in handy and have their own perks. Tell us what you think in the comments.
Top python Books to learn Python programming language.
For reference

Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

follow dataflair on YouTube

2 Responses

  1. Rob says:

    >>> iter([1,2]).__sizeof__()
    16
    The iter() of a list is indeed small, but… the list itself will be referenced and therefore remain in memory until the iterator is also destructed. So to compute the total memory used by this iterator, you also need to add the size of the object it iterates
    >>> [1,2].__sizeof_()
    56

    The generator wins in memory efficiency, by far!

  2. DataFlair says:

    I think you are asking that we are getting output as 56 on executing the code ‘[1,2].__sizeof_()’. And this shows that generators are more memory efficient. But one thing to notice here is that [1,2] is an iterable object and iter([1,2]) gives an iterator object. Both are used for iteration, but they’re different. In this article, we are comparing iterators and generators and thus, iterators are more efficient in terms of memory.

Leave a Reply

Your email address will not be published. Required fields are marked *