• Animal
  • Auto
  • Computers
  • Education
  • Finance
  • Health
  • Math
  • Mobiles
  • Programming
  • Science
  • Sports
  • Technology
  • Terms
  • Web

  • Difference Between Iterators and Generators in Python

    Iterators vs Generators in Python

    Iterator and Generator in Python are type of enumerators in Python. Both are used to iterate from start to end of List data-structure. Below we will talk about the Differences between Python Iterators and Generators so that you will know which one to use when in python?.

    Difference Between Perl and Python

    What is the difference between Iterator and Generator in Python?


    1. Iterator can be used to any object whose class has a next() method and an __iter__ method that does return self.
    2. When you create a list, you can read its items one by one, and it’s called iteration:
    3. You can call iterator in python if you could you run through the elements using “for…in…” loop. But, all values in the list or string or file is in memory. If the data structure is huge then you end up using lot of memory.
    4. Using iterator you can iterate the data structure multiple times.

    Generator in Python

    1. Every generator is an iterator, but not vice versa. A generator is built by calling a function that has one more yield statements/expressions and whose class has a next() method and an __iter__ method that does return self
    2. Generators are also iterator, but you all the values below are generated on the fly and are not stored in the memory.
    3. From the above example you can see the difference is the list comprehension example uses () for generator and [] for iterator.
    4. Using generator you can only iterate the data structure once.

    These are the Difference between Iterator and Generator in Python, If you know more differences, Do contribute by leaving the comment. I will be happy to add them in this post.

    Posted under: Programming
    1957 readers are already subscribed to this blog! Why don't you be one of them? Subscribe to this blog via your favorite RSS feed reader or by entering your email address on the form below:

    Leave a Reply

    page counter
    NiharsWorld on Twitter NiharsWorld on Facebook NiharsWorld RSS Feed