A Simple Guide to Difference Between Python Yield and Python Return – Python Tutorial

By | July 8, 2019

Python yield and return statements are common used in python function, both of them can control the execution process of python function, in this tutorial, we will discuss some differences between them.

python yield and return difference

Yield Return
Return a generator obj Return a value or obj
Suspend a functon execution and save its status, function can be executed again. Suspend a functon execution, function can not be executed again.

About Python yield, you can read tutorial.

Understand Python yield Statement for Beginners – Python Tutorial

Then we write an example similar to pyhton yield to express the usage of python return.

Create a return example

def returntest():
    print ('return 1')
    return 1
    print ('return 2')
    return 2
    print ('return 3')
    return 3
    print ('end')

m = returntest()

Print type and value of m

print (type(m))
print (m)

The output is:

return 1
<class 'int'>
1

From the output, we will find:

1. m is an int, not a generator, because returntest() return 1

2. the value of m is 1

3. when returntest() call return 1, it is suspended and not executed contiously.

Leave a Reply

Your email address will not be published. Required fields are marked *