Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

How to use yield and return statements in Python

Jennifer OU

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 function
def test_yields():
    yield 'Item 1'
    yield 'Item 2'

# Assigning the generator function
iter_object = test_yields()

# Each time the generator function is invoked it returns a different item
print(next(iter_object))
print(next(iter_object))

# Printing out the variable iter_object returns a generator object
print(iter_object)
A function with a yield statement (generator function)

Code explanation

  • Line 2: We define the generator function, test_yields().
  • Lines 3 and 4: The test_yields() function yields two items; item 1 and item 2.
  • Line 7: We assign test_yields() to the variable iter_object.
  • Lines 10 and 11: The next()Built-in function that returns the next item in an iterator function is used to print out the next item in the generator function test_yields().
  • Line 14: We print out the iter_object without the next() 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 function
def test_return():
    return 'Item 1'
    return 'Item 2'

# Function exit at the first return statement
print(test_return())
print(test_return())
A function with the return statement

Code explanation

  • Line 2: We define the function test_return().
  • Lines 3 and 4: The test_return() function returns two items; item 1 and item 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.

RELATED TAGS

python
communitycreator
RELATED COURSES

View all Courses

Keep Exploring