What does "yield" mean?

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.
Popular articles