×

Difference between Yield and Return in Python

Python yield statement

The generators are defined by using the yield statement in Python. Generally, it converts a normal Python function into a generator. 

The yield statement hauls the function and returns back the value to the function caller and restart from where it is left off. The yield statement can be called multiple times. While the return statement ends the execution of the function and returns the value back to the caller. The function returns nothing without it. In Python generators, the yield function is used for replacing the return function that sends back the value to the user without ruining local variables.

What is Generator?

Python generators are used as a method for generating the iterators. Generators have automatically handled the task. A generator can be defined as the special function that returns an object of the generator to the caller.

In simple words, a generator is referred to the function that returns an iterator that we can iterate upon. In Python, it is very easy to create a generator and it uses the yield statement instead of the return statement.

Example 1:

# Python Code for using yield statement 

def myfunction(a, b):

add = a + b

yield add

sub = a - b

yield sub

mul = a * b

yield mul

div = a % b

yield div

# generator runs with for loop for getting all values

for value in myfunction(49,45):

print(value)

Output:

94

4

2205

1.08

Example 2:

# Python code for using the yield statement

def printoutput(String) :

    for i in String:

        if i == "a":

            yield i

# string initialization

String = "Tutorial and examples"

ans = 0

print ("The number of 'a' in the string is : ", end = "" )

String = String.strip()

for j in printoutput(String):

    ans = ans + 1

print (ans)

Output:

The number of 'a' in the string is : 3

Python Return Statement

The return statement is generally used for the execution ending and returns the value back to the caller. The return statement can return all types of values and it returns nothing when there is no expression passed to return statement. There can be multiple return statements in a function but only a single statement is called for any specified invocation of the function.
We can see a return statement is placed at the end of the block of the function for returning the final output of the execution of all statements inside the function. Also, it can be seen earlier in the block of the function for stopping the execution of all consequent statements in the block. The execution of the program at the caller is quickly restarted with a return statement. It returns none when no value is specified.

Example 1:

# Python code for 

#demonstrating use of return statement

def myfunc(a, b):

    add = a + b

    sub = a - b

    mul = a * b

    div = a % b

    return(add, sub, mul, div)

    # Getting return value and printing the output

    output = myfunc(49,45)

    print("Addition: ", output[0])

    print("Subtraction: ", output[0])

    print("Multiplication: ", output[0])

    print("Division: ", output[0])

Output:

Addition: 94

Subtraction: 4

Multiplication: 2205

Division: 1.08

Example 2:

# Python code for 

#demonstrating use of return statement

class check: 

    def __init__(self): 

        self.str = "Tutorial and examples"

        self.x = "Kaushal"   

# Object of test will be returned by this function

def fun(): 

    return check() 

# Driver code for checking the above method

t = fun()   

print(t.str) 

print(t.x)

Output:

Tutorial and examples 
Kaushal

Difference between yield and return Statement

yield Statementreturn Statement
Yield returns the generator object.Returns the results to the caller.
It can run multiple times.It runs only a single time.
Code can be executed in the next function call after the yield statement.Code will not be executed after the return statement.
This statement can resume from where it is left off or paused.The function call in this statement only runs the function from the beginning.
The yield statement hauls the function and returns back the value to the function caller.The return statement takes exit from the execution and returns the value back to the caller.

Conclusion

In the above article, we have seen the differences in the return and yield statements. Also, we have understood the concepts of both statements and know how to use them in our Python programs. 


Related Topics

Python PyMOTW

The cmd module comprises one class of the general public, Cmd, meant for command processors such interactive shells and other command interpreters as a foundation class. It utilises readline as...

3 minutes read.

How to create a class in python

In any programming language, a class is a user-defined plan or blueprint using which objects or instances of the class are created. You may wonder why we need classes in programming....

5 minutes read.

What is the Python Global Interpreter Lock?

Introduction When working with processes, Python employs a form of process lock called the Global Interpreter Lock (GIL). Python typically executes a collection of typed statements using just one thread. It...

4 minutes read.

Python History

Python is one of the top trending, widely-used programming languages. Python is a general-purpose programming language. Python language is known for its features. Some features are given below: SimplisticFree and open...

4 minutes read.

Python Bubble Sort

Bubble sort is one of the techniques used to sort the elements in lists in a certain order, either in ascending or descending order. It is called Bubble sort because...

4 minutes read.

How To Print Colored Text in Python

Changing the colour of certain parts of a string when printing the output of a Python programme to the terminal may make it easier to read. We can approach this...

3 minutes read.

Permutations in Python

Recursion Basic idea: for numbers of length N. N-1 items are chosen at random between 0 and then generate permutations using the remaining N-1 elements in a recursive fashion. Once you've done...

4 minutes read.

Python pycountry

What is Pycountry? Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations...

4 minutes read.

Bar Plot in Python

A bar chart or bar graph displays categorical data using rectangular bars with heights or lengths proportionate to the values for the data distributed in the dataset. In a bar...

16 minutes read.

Python Dictionary keys() method

Python Dictionary keys() method The dictionary.keys() method in Python returns a view object that displays a list of all the keys in the dictionary Syntax dictionary.keys() Parameter NA Return This method returns a view object that displays...

2 minutes read.

Python program to find factorial of a given number

Python program to find factorial of a given number Factorial is a non-negative integer. It is the product of all positive integers from 1 to the number we are going to...

3 minutes read.

XXhash Python Examples

XXhash Python: xxHash is an extremely rapid hash calculation that operates inside the confines of RAM. Code is incredibly convenient, and hashes (almost nothing/large endian) are same at all levels. Execution of...

4 minutes read.

List Comprehension in Python

Sometimes we need new lists that are completely based on previously existing lists, so to perform this operation successfully, some of the programming languages come with a syntactic construct known...

5 minutes read.

Python Set symmetric_difference_update() method

Python Set symmetric_difference_update() method The set.symmetric_difference_update() method in Python updates the original set by removing items that are present in both sets and inserting the other items of the set. Syntax set.symmetric_difference_update(set1) Parameter set- This parameter represents the first...

2 minutes read.

Implementing geometric shapes into the game in python

Geometric Drawings We are trying to draw various shapes of geometry by using pygame module to implement Geometric Drawings in game. Let us revise few syntax of basic shapes, to get started...

7 minutes read.

Python Comments

In this tutorial, we will discuss the importance of comments in the Python code and how various types of comments can be inserted in the code. Comments are used to describe...

3 minutes read.

Python elif

Python elif The elif statement is used to check multiple conditions and execute the specific block of statements depending upon the true condition among them. Syntax if expression1: statement elif expression2: statement elif expression3: statement else: statement The elif statement can be optional...

3 minutes read.

Python Dictionary

Dictionary in Python is an unordered collection of data values, which is used to store data values like a map. Unlike different data types that hold just individual assets as...

4 minutes read.

Exponentiation in Python

What is an Exponent in Python? Exponent is a fundamental mathematical concept that is used in many different areas, such as engineering, physics, and finance. In mathematics, an exponent is a...

4 minutes read.

Python Program for Tower of Hanoi

In this tutorial, we will examine and learn about the Python coding used to create the video game Tower of Hanoi. Before seeing the game's step-by-step implementation in Python, we...

3 minutes read.