+ 1

How "Generator" work in Python?

I can't get the process of Generator

8th Feb 2019, 3:59 AM
Phyoe Min Thant
Phyoe Min Thant - avatar
2 Answers
+ 3
You can use yield instead of return in your function definition, then you get a generator. It will not terminate after the first yield like a normal function would after return, but give out what's to be yielded, then jump right back in at this point next time you use it, and go on with business until the next yield. Take a look at two examples: In the first one, permutations are searched; everytime one is found, it will be given out. In the second one, the adjacent points of a 2d array are returned one after another. https://code.sololearn.com/c7Xh8cE8kSy0/?ref=app https://code.sololearn.com/c30wK7XUZeo3/?ref=app
8th Feb 2019, 8:05 AM
HonFu
HonFu - avatar
+ 3
It creates an iterator, which can't be indexed, but can be iterated through using for loops. One of it's advantages is that it doesn't store the values it yields in one stack once. You can use the iterator before it is fully created. You can index it's values by converting it to a list with the list() constructor.
8th Feb 2019, 8:53 AM
Seb TheS
Seb TheS - avatar