Yield
is a keyword that is used like return
, except the function will return a generator.
What is a Generator?
Generators are iterators, a kind of iterable you can only iterate over once. Generators do not store all the values in memory, they generate the values on the fly.
mygenerator = (x*x for x in range(3))
print(mygenerator)
>>> <generator object <genexpr> at 0x00000219B77ED0C8>
# Iterate over the generator
for i in mygenerator:
print(i)
>>> 0
1
4
# Try printing the above again
for i in mygenerator:
print(i)
>>>
See how nothing is printed anymore. You can only iterate once.
Check out this video to learn about generators and Yield in details.