Yield is a keyword that is used like return, except the function will return a generator, so lets first understand the generator -
Generators are iterators, but you can only iterate over them once. It’s because they do not store all the values in memory, they generate the values on the fly:
>>> mygen = (x*x for x in range(3))
>>> for i in mygen:
... print(i)
Output
0
1
4
you can not perform for i in mygen a second time since generators can only be used once.
Now coming back to yield which by definition is a keyword that is used like return, except the function will return a generator, see the following example for more clarity -
>>> def createGenerator():
... mylist = range(3)
... for i in mylist:
... yield i*i
...
>>> mygen = createGenerator()
>>> print(mygen)
Output
0
1
4