DEV Community

Cover image for Python Generator - Yield and Next
Divyanshu Shekhar
Divyanshu Shekhar

Posted on

Python Generator - Yield and Next

Generators In Python

A Generator in Python is a sequence creation object i.e iterator. The Generated Iterator can contain a huge sequence.

Even though the generated sequence is pretty huge, it can be successfully iterated.

This is possible because the generator does not create and store the sequences in the memory at once, but it creates the sequence on the fly. This also saves memory usage of the program.

Creation of an iterator in python is a pretty heavy task, we have to create a class with iter() and next() methods, and also have to handle errors.

These steps are automatically performed by the Python Generator and return an iterator.

That’s why python generators have become so popular.

Generator Creation In Python

Image Source –
In this example, we are going to make a ranger generator function. This will be the copy of range() function in python.

The range() function also returns a generator object and then it can be iterated.

Range function python

r = ranger(0, 10)
Output: range type
<class 'generator'>
Enter fullscreen mode Exit fullscreen mode

Learn more about Python Generators from the Original Post.

Top comments (0)