Try it here
Difference between generators and iterators

Generator vs. iterator in Python


An iterator in Python serves as a holder for objects so that they can be iterated over,a generator facilitates the creation of a custom iterator.

A generator is always an Iterator but Iterator is not always a generator.

A list is iterable but not an iterator, but if we run dunder iter method(__iter__()) on a list, it returns an iterator.

Any object that has a __next__() method is an iterator.

The following are some main differences between Generator and iterator:

Generator Iterator
Implemented using a function. Implemented using a class.
Uses the yield keyword. Does not use the yield keyword.
Usage results in a concise code. Usage results in a relatively less concise code.
All the local variables before the yield statements are stored. No local variables are used.


Generator :

Remember that a return statement terminates the execution of a function entirely, whereas, the yield statement saves the function state and resumes its execution, from this point, upon subsequent calls.

def my_range(start, end):
    current = start
    while current < end:
        yield current
        current += 1

Note -Generators are iterators in which __iter__ and __next__ are created automatically by yield keyword.


The __iter__() method returns the iterator object. This is required to allow an iterator to be used with the for and in statements.

The __next__() method returns the next element in the sequence. In the case of a finite iterator, once it reaches the end (defined by the termination condition), all of the subsequent calls to this method should raise an exception.

class MyRange:
    def __init__(self, start, end):
        self.value = start
        self.end = end

    def __iter__(self):  # For something to be iterable, it needs to have __iter__() method
        return self

    def __next__(self):  # For something to be iterator, it needs to have __next__() method
        if self.value >= self.end:
            raise StopIteration
        current = self.value
        self.value += 1
        return current

nums = MyRange(1, 10)
for num in nums:

Writer profile pic

Nupur on Dec 14, 2020 at 12:12 am

This article is contributed by Nupur. If you like and would like to contribute, you can write your article here or mail your article to . See your article appearing on the main page and help others to learn.

Post Comment

Comments( 0)


Forgot Password

Please enter your email address below and we will send you information to change your password.