×

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

__init__ in python

Every programmer will enclose to object-oriented programming (OOP) these days. As we know, that python is the latest and most modern programming language; python supports to implementation of object-oriented philosophy....

5 minutes read.

Creating new Database using Python MySQL

In this article, we are going to discuss how to create a new database by connecting Python and MySQL. What is a Database? The places or memory used to secure highly and...

6 minutes read.

Python String splitlines() method

Python String splitlines() method The string.splitlines() method in Python splits the specified string and returns a list of the lines in the string, breaking at line boundaries.  Syntax splitlines([keepends]) Parameter keepends(optional): This parameter specifies if...

1 minute read.

Python String rfind() method

The string. rfind() method in Python returns the highest index in the string if the substring sub is found else it returns -1 if the substring is not found. Syntax string.rfind(sub [,start [,end]]) Parameter sub: This parameter...

2 minutes read.

Python Algorithms

A quote goes, "A goal without a plan is just a wish." To achieve anything in life, we can't simply go for it without making a plan and sticking to...

4 minutes read.

Python Marshmallow

Python:  Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

How to check version of Python

How to check version of python The versions of Python come with different kinds of features and functionalities. It is not a herculean task to keep track of the updates these...

3 minutes read.

Curdir Python

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 in a...

3 minutes read.

Python Word Tokenizer

Python Overview Python is an Object-Oriented high-level language. Python is designed to be highly beginner-friendly. Python has an English-like syntax, which is very easy to read. Python is an interpreted language...

4 minutes read.

Find Words in String Python

Python : Python programming language is considered a general purpose; it is a high-level programming language that is not much difficult but easier to learn. Python programming language is rich in...

5 minutes read.

How to Convert int to str in Python

How to Convert int to str in Python In the last article, we studied how we convert a variable with string datatype to integer datatype and discussed different data types available...

4 minutes read.

Python Syntax Error Invalid Syntax

Python is renowned for its simple and direct syntax. However, we might come across some things that Python doesn't allow if we are learning Python for the very first time or if...

14 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 add 2 lists in Python?

In Python, a list is defined as a data structure that contains a sequence of elements. It can contain any kind of data type inside it but in order to concatenate two...

3 minutes read.

Python Linked List

Linked List Linked lists non-contiguous linear data structure which is made up of nodes and used to store value and a pointer pointing to the next node. It is linked with...

6 minutes read.

Spotify API in Python

The application programming interface is referred to as API. In essence, an API serves as a layer of communication or, as the name suggests, an interface that enables systems to...

3 minutes read.

Io stringio Python

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 in a...

7 minutes read.

Gethostbyname() function in Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

Python TypeError

What is TypeError in python? TypeError is one of the exceptions in the python programming language. This exception occurs when an operation is performed on an unsupported object type or can...

6 minutes read.

Python List Size

Introduction The list data type in Python is an ordered, flexible collection. A list may also contain duplicate entries. To get the size of any object, use the len() function in...

6 minutes read.