Python yield Keyword
Example
Return three values from a function:
def myFunc():
yield "Hello"
yield 51
yield
"Good Bye"
x = myFunc()
for z in x:
print(z)
Try it Yourself »
Definition and Usage
The yield keyword turns a function into a function generator.
The function generator returns an iterator.
The code inside the function is not executed when they are first called, but are divided into steps, one step for each yield, and each step is only executed when iterated upon.
Unlike the return keyword which stops
further execution of the function, the yield
keyword returns the result so far, and continues to the next step.
The return value will be a list of values, one item for each
yield.
More Examples
Example
Note that the code inside the function is not executed when calling the function, it is only executed when the returned iterator is iterated upon:
y = 0
def myFunc():
global y
y = 10
yield "Hello"
y = 20
yield 51
y = 30
yield "Good Bye"
#The function is called:
x = myFunc()
#But y is still 0:
print("At
this point, y is still:", y)
#Run the first iteration:
next(x)
#And y becomes 10:
print("Now, y is:", y)
#Run another
iteration:
next(x)
#And y becomes 20:
print("Now, y is:", y)
#Run another iteration:
next(x)
#And y becomes 30:
print("Now, y is:", y)
Try it Yourself »
Related Pages
Use the return
keyword to return only one value, and stop further execution.
Read more about functions in our Python Functions Tutorial.