Python yield Keyword

Used to return a generator from a function.

Example

Python
def get_generator():
   i = 0
   while i < 10:
       yield i
       i = i + 1

The code above will return a generator, which we can use as follows

Python
gen = get_generator()

for value in gen:
    print(value)

Output

0
1
2
3
4
5
6
7
8
9

Notes

An iterator is an object that contains a set of items that can be iterated over.

A generator is an iterator that can be traversed once only. A generator doesn't have all the values stored in memory - it generates each value on the fly (this is what the yield keyword is doing: sending back each value one by one)

It's important to understand that a generator function is not run until the generator that it returns is actually iterated.

Python
# get_generator returns a generator, but no code has actually been run.
gen = get_generator()  

# By using the generator, we will now actually call the generator function
for x in gen:          
    # With each loop, the yield keyword in the generator function will
    # return a new value until the generator function ends
    print(x)