+ 3

yield keyword

I had came across an example related to yield keyword. def generator(): for i in range(6): yield i*i g = generator() for i in g: print(i) OUTPUT: 0 1 4 9 16 25 I am not understanding, how after print(i) again generator is accessed and yield is used. I know that using yield we can traverse a sequence but if yield is given to g and then it is printed how it automatically goes back to generator() again.

8th May 2019, 4:46 PM
harshit
harshit - avatar
2 Answers
+ 9
A commented example of how yield and generators can be used: https://code.sololearn.com/cOGvT24D3Of9/#py
8th May 2019, 5:34 PM
CĂ©pagrave
CĂ©pagrave - avatar
+ 5
Everytime you call a generator function, it will return an object that you can traverse as you defined in the function. So you could store different objects in different variables, and every object would remember the point it's at. Such an object proceeds to the next yield statement whenever you use 'next', either a single time or in a loop, until it's exhausted. If you next one object, it will have no effect on another.
8th May 2019, 4:54 PM
HonFu
HonFu - avatar