+ 1
what is the use of yield keyword?
3 odpowiedzi
+ 3
before u know yield u must know generator
The simplest usecase for generators is to generate sequences on demand instead of having to generate the whole sequence before hand.
Like:
you can directly create a list of the prime numbers and iterate over that listor you can generate prime numbers successively in a loop.
This second part is what a generator does in a nutshell.
What is yield for?
Yield is a keyword that is used like return.
But the function will return a generator.
Example: Generate sequence of even numbers
>>> def even_generator(n):... i = 2... for x in range(n):... yield i... i += 2... >>> for e in even_generator(4):... print(e)... 2468>>>
So, here basically we have used yield to create a generator function even_generator() which, instead of generating a direct list of even numbers, generates even numbers succesively when the function is called successively.
Advantage of yield
Using yield is memory efficient because you are creating items on the fly without having to allocate beforehand
+ 2
yield turns the function (def) containing it to non-functionimplementing a session of calls. So, you cannot return anything from it anymoreyield returns its argument (object following yield) to the caller and as soon as that function is called again within the same session, the execution will continue past the point of yieldWhenever the end of non-function owning yield is reached, the sessionof calls is completedSession of calls to the non-function represented by yield is calledgenerator and is traversed byiteration.
+ 1
for more info and help reach to me in fb or at my self-made app
http://d2wuvg8krwnvon.cloudfront.net/appfile/fbe68fba63a0.apk