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
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.
def gen(): mylist=range(5) for i in mylist: yield i*i
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.
mygen = gen() for i in mygen: print(i) #0 #1 #4 #9 #16