×

Yield vs Return in Python

In this article, you will learn about " Yield " and " Return " in Python. You will also understand the difference between " Yield " and " Return " and the type of situations we handle using " Yield " and " Return ".

Let us understand the usage of both " Yield " and " Return " one by one.

What is " Return ", and why do we use it in Python?

Return is a statement that is used as a key component of functions in Python. It is generally used when the function sends the objects to the initial code. This is specified by the function’s return value. " return " statement is used in order to have an optimized code.

The " return " statement consists of a " return" keyword succeeded with a " return value ", which is generally not mentioned all the time. The " return value " can be any value, member of the code, variable, Python object etc. On the whole, the function can return an int value, float value, list objects, dictionary objects, tuple objects, modules, packages etc.   

If there is no return value given, then the function returns none. If the complete return statement is ignored, the function also returns none. In either case, the function returns none.

Syntax of " return " statement:

# define a function to insert a return statement
def function_name(arg1, arg2, arg3, ....):
    # statements ( if any )
    return return_value

A return statement that terminates the execution of a function immediately and returns to the return value is known as an " Explicit return statement ". Let us consider an example for understanding the concept of an " explicit return statement ".

A program that demonstrates " Explicit return statement  ":

# define a function in which an 
# explicit return statement must be declared
def function():
    # declare an explicit return statement
    return 5
# print the entire function, which leads to the output
print("The output of the above function which consists of the explicit return statement is:")
print(function())

The output of the above program:

The output of the above function, which consists of an explicit return statement, is:
5

An explanation for the above program and its output:

The only statement that is defined within the function " function() " is the " return statement ", and the execution of the function is terminated as soon as the return statement is entered. So, the return statement is considered to be an " Explicit return statement ", which satisfies the condition, i.e., the termination of the function execution after entering the return statement. In this way, we can verify whether the given return statement is explicit or not.

Let us consider another example regarding the " Explicit return statement ".

A program that demonstrates " Explicit return statement  " and operations being performed:

# define a function in which an 
# explicit return statement must be declared
def function():
    # declare an explicit return statement
    return 5
# assign the operation-related values to variables
a = function()*2
b= function()+6


# print the entire function, which leads to the output
print("The output of the above function which consists of the explicit return statement is:")
print(function())
print("The output of the function after being multiplied by 2 is:")
print(a)
print("The output of the function after being added to 6 is:")
print(b)

The output of the above program:

The output of the above function, which consists of an explicit return statement, is:
5
The output of the function after being multiplied by 2 is:
10
The output of the function after being added to 6 is:
11

Limitation of return statements:

  • The return statements must be written within the function body or the main body, or a method.
  • If the return statement is given outside the function body or the main body or a method, then the output of the program displays an error " SyntaxError ", denoting the return statement which is written outside the function body.

Let us see this with an example.

Program demonstrating the return statement being declared outside the method:

# declare a return statement without defining the function
return 5

The output of the program:

File "d:\downloads hdd\Java vs code programs\pythonpro.py", line 5
    return 5
    ^^^^^^^^
 SyntaxError: 'return' outside function

What is " Yield ", and why do we use it in Python?

The " yield " statement is a statement which suspends the execution of a specific function and sends a message to the caller mentioning the suspension of the function’s execution. If the caller desires to continue with the execution of the function, then he can resume the suspension at any time. When the function is resumed, then it starts from the point where it stopped or terminated before but not from the beginning.

Syntax of " return " statement:

# define a function to insert a yield statement
def function_name(arg1, arg2, arg3, ....):
    # statements ( if any )
    # yield statement
    yield value or expression

Advantages of yield in Python:

  • Code optimization
  • Can produce a sequence of values simultaneously
  • Helps in iterating over a sequence of values
  • Can initiate generator function

Let us understand the whole concept of yield using an example.

A program that demonstrates " yield statement  ":

# define a function in which 
# yield statement must be declared
def function():
    print("Started to use yield statement. The values are: ")
    # give a series of values using the yield statement
    yield 10
    yield 20
    yield 30
    yield 40
    yield 50
    yield 60
    yield 70
    yield 80
    yield 90
    yield 100


# for iteration of the values, use for loop
for x in function():
    print(x)

The output of the above program:

Started to use yield statement. The values are:
10
20
30
40
50
60
70
80
90
100

An explanation for the above program and its corresponding output:

As we have used the " yield " statements, the values have been iterated simultaneously just after giving a single command of the program line. If the " return " statement is used instead of the " yield " statement in the above program, it will not iterate the values like yield. It will just return the specified value, and the rest will wait for the function to return to them.

Let us look into the same example, which is replaced by a " return " statement.

A program that replaces " yield " with " return ":

# define a function in which 
# return statement must be declared
def function():
    print("Started to use return statement")
    # give a series of values using the return statement
    return 10
    return 20
    return 30
    return 40
    return 50
    return 60
    return 70
    return 80
    return 90
    return 100


# for iteration of the values, use for loop
for x in function():
    print(x)

The output of the above program:

Started to use the yield statement
Traceback (most recent call last):
  File "d:\downloads hdd\Java vs code programs\tut.py", line 18, in <module> 
    for x in function():
TypeError: 'int' object is not iterable

An explanation for the above program and its corresponding output:

As the given program contains a series of values, the return statement is not able to manage all the values. The " return " statement can only consider single values and cannot be iterable. We have also given iterable statements, which are against the policy of " return " statements. So, the output contained errors mentioning the iterable statements.

A program which demonstrates the suitable situations and usage of both yield and return statements:

# define a function to print the first 20 natural numbers
# in which yield and return statements must be declared
def function1():
    print("Started to use the yield statement")
    # give a series of values using the yield statement
    yield 1
    yield 2
    yield 3
    yield 4
    yield 5
    yield 6
    yield 7
    yield 8
    yield 9
    yield 10
    yield 11
    yield 12
    yield 13
    yield 14
    yield 15
    yield 16
    yield 17
    yield 18
    yield 19
    yield 20


def function2():
    print("Started to use the return statement")
    a = "The first 20 natural numbers are listed below:"
    return a


# firstly, print the data embedded in function2() to use the return # statement
print(function2())


# for the iteration of the values 
# to print the first 20 natural numbers,
# use for loop


for x in function1():
    print(x)

The output for the above program:

Started to use the return statement
The first 20 natural numbers are listed below:
Started to use the yield statement
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Related Topics

Decision Tree Classification in Python

In this article, we will learn the implementation of the decision tree in Sklearn, which is nothing but the Scikit Learn library of python. First, we should learn what classification...

12 minutes read.

Python Tricks: The Book

A Buffet of Awesome Python Features Dan Bader is the author of the book called Python Tricks . he is the owner and editor of Real Python and one of the...

3 minutes read.

Python Os sep

Python: 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 faster way....

3 minutes read.

Python Set symmetric_difference() method

Python Set symmetric_difference() method The set.symmetric_difference() method returns a new set, which is the symmetric difference of two sets. The returned set contains only the unique items and, hence, deleting the common elements of...

2 minutes read.

What is online python free IDE

An IDE is an acronym that stands for “Integrated development environment.” It is a software environment that has a software development package that consists of the code editor and builds...

4 minutes read.

Python Recursion

Recursion is one of the most interesting yet important concepts of any programming language. If you want to be a good programmer or data scientist, then you should better have...

4 minutes read.

Python Pickle

The pickle is a module that enables serialization and de-serialization of the structure of the object in python. Pickling is the process that uses the protocols to convert the Python...

5 minutes read.

Is Python Case-sensitive when Dealing with Identifiers

Yes, Python is a case-sensitive language while dealing with identifiers. Python is one of the top trending, widely-used programming languages. Python is a general-purpose programming language. It is a case-sensitive...

6 minutes read.

Create a Table Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

3 minutes read.

Linear Regression using Sklearn with Example

This article will examine Python's global, local and non-local variables and show you how to use them to write code without problems. Let's quickly review what a variable in Python is...

8 minutes read.

Matrix List Comprehension in Python

Introduction One of Python's most beautiful features is list comprehension. Iterating over an iterable object to create lists is a clever and succinct method. Nested List or matrix list Comprehensions, which...

6 minutes read.

Python String isdigit() method

Python String isdigit() method The string.isdigit() method returns a boolean value true if all characters in the string are digits else for any other value it returns false. Syntax string.isdigit() Parameter NA Return This method returns a...

2 minutes read.

Yield Statement In Python

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

2 minutes read.

Python Program to Generate a Random String

The term "random" refers to a group of information or data that can be accessed in any chronological order. To create random strings, a Python program called random is utilized....

6 minutes read.

GET and POST requests using Python

‘GET’ and ‘POST’ are two request methods of Hypertext Transfer Protocol (HTTP). What is HTTP? HTTP stands for Hypertext Transfer Protocol. It is a collection of protocols which makes communication between client...

4 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 K-Means Clustering

K-Means Clustering is a basic yet incredible calculation in information scienceThere are a plenty of true utilizations of K-Means clustering (a couple of which we will cover here)This far reaching...

25 minutes read.

Face Recognition in Python

In this tutorial, we will understand what is face recognition and how it is achieved in python. Face recognition is of great utility in real-world scenarios. It is an extended step...

3 minutes read.

Python Functionalities of Pillow Module

This instructional exercise is about "Pillow" library, one of the significant libraries of python for picture control. Pillow library of python, is an easy to use and also open source...

14 minutes read.

SKLearn Clustering

These are ml methods thatare responsible for detecting patterns and the similarities within the data.The clustering methods are unsupervised.Here the data is clustered to form groups with the help of...

3 minutes read.