WHAT DOES "YIELD" MEAN?
7 min
Oct 12 2020
When reading someone else’s code, you can come across many incomprehensible constructions. And now I want to briefly highlight such a construction as yield. Yield is a keyword that is used in the same way as return. The difference is that the function starts returning a generator instead of a value.
def generator ():
    for i in (1, 2, 3):
        yield i
g = generator ()
print (g)
<generator object generator at 0x2e58870>
for i in g:
    print (i) 1 2 3
In this case, from a practical point of view, this is a useless example. You will get a tangible benefit in a situation where your function must return a large enough amount of data, but you only need to use it once. In order to fully master the yield statement, you should know that when you call a function that has yield in its body, that function does not execute. Instead of executing, the function will return a generator object. It looks a little strange at first glance - the function was called, but the code was not executed, but just remember this fact. The code will be executed on each iteration - whether it is a for <...> in loop or a call to the .next() method.
BLOG LATEST
Popular articles
GOT AN IDEA? LET'S DISCUSS!
Share your project’s scope, timeline, technical requirements, business challenges, and other details you consider necessary. Our team will study them and contact you soon. Let’s make an exciting product together!
By sending this form I confirm that I have read and accept the Privacy Policy
WELCOME TO OUR OFFICES
Georgia
Russia