Python Yield Keyword To Create Generator

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/python-yield-keyword-to-create-generator/
PINTEREST
PINTEREST
INSTAGRAM

Python provides different features some of them do not exists in other programming languages. In this tutorial we will look one of them. yield keyword is used with generators. Generators are some iterative mechanisms which iterates and generates some values. yield simply holds current values and variables of the scope which is generally a function. This gives us we can resume where we left.

yield acts like a return for a function but difference is that all local variables and situation hold and do not change after called functions returns back to the yield block.

Defining Iterators with yield

The best way to lear yield is writing some code about it. The problem with calling functions is that there will be a lot of memory consumption if there are a lot of functions. But we will use yield and which will optimize memory usage.

We will write a generator which is a function but this function will be converted into a generator.

Create Generator Instance

We have defined generator but created a one. We will simply create generator like a class initialization and use like a list. But under the hood it is a generator and generates list of values when used in while , for or similar structures.

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/python-yield-keyword-to-create-generator/
PINTEREST
PINTEREST
INSTAGRAM

LEARN MORE  In Python Operator Usage Tutorial with Examples

You may also like...

Leave a Reply

Your email address will not be published.

Enjoy this blog? Please spread the word :)