How to use yield and return statements in Python
Overview
The yield and return statements are used to output expressions in functions.
A function pauses at a yield statement and resumes at the same place upon re-execution. A function fully exits at the encounter of a return statement without saving the function’s state.
Syntax
The syntax for the yield statement is given below:
yield expression
Code
We’ll use the yield statement in the code below:
# Defining the generator functiondef test_yields():yield 'Item 1'yield 'Item 2'# Assigning the generator functioniter_object = test_yields()# Each time the generator function is invoked it returns a different itemprint(next(iter_object))print(next(iter_object))# Printing out the variable iter_object returns a generator objectprint(iter_object)
Code explanation
- Line 2: We define the generator function,
test_yields(). - Lines 3 and 4: The
test_yields()function yields two items;item 1anditem 2. - Line 7: We assign
test_yields()to the variableiter_object. - Lines 10 and 11: The
function is used to print out the next item in the generator functionnext()Built-in function that returns the next item in an iterator test_yields(). - Line 14: We print out the
iter_objectwithout thenext()function to return a generator object.
A function with a yield statement (generator function) returns a generator object. A generator is a type of iterator. Each item in the generator object can be retrieved in sequence by using the next() function.
Syntax
The syntax for the return statement is given below:
return expression
Code
We’ll use the return statement in the code below:
# Defining the functiondef test_return():return 'Item 1'return 'Item 2'# Function exit at the first return statementprint(test_return())print(test_return())
Code explanation
- Line 2: We define the function
test_return(). - Lines 3 and 4: The
test_return()function returns two items;item 1anditem 2. - Lines 7 and 8: We invoke the
test_return()function twice and print out the result.
The test_return() exits immediately after the first return statement. It only returns item 1, even after re-execution, because the previous state of test_return() is not saved.