×

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

Adding item to a python dictionary

The dictionary is one of python’s built-in data structures where it stores key-value pairs. A dictionary is a collection of ordered values that can be changeable. We can add, modify,...

3 minutes read.

Python reversed() Function

Python reversed() Function The reversed() in Python returns a reverse iterator. Syntax reversed(seq) Parameter seq: This parameter represents any iterable object. Return This function returns a reversed iterator object. Example 1 # Python Program describing # the reversed() function ...

1 minute read.

Python program to find the greatest among two numbers

Python program to find the greatest among two numbers We have many approaches to get the largest number among the two numbers, and here we will discuss a few of them....

2 minutes read.

Count Number of Keys in Dictionary Python

Dictionary is a particular data type in python. Dictionary stores unique values by taking different keys and their assigned values. Through this article, we will learn about python dictionary count,...

3 minutes read.

Artificial intelligence mini projects ideas in python

Artificial intelligence "The human race started from the invention of the wheel", and today we are about to advance to the Industrial level 4.0, where machines can work, talk, think and...

6 minutes read.

Convert uppercase to lowercase in Python

Python String lower() By using the built-in string lower() method, all the uppercase characters can be converted into lowercase characters in a string, The lowercased string from the given string is returned...

1 minute read.

What is Python compiler GDB?

The source code of one programming language is converted into machine code, bytecode, or another programming language by a compiler, a specialised software. A compiler is a tool that converts high-level...

3 minutes read.

Writing to a CSV file in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

6 minutes read.

List Assignment Index out of Range in Python

As we know, a List is one of the four unique data structures available in Python; In this tutorial, we will deep dive into understanding iterating through a list and...

3 minutes read.

How to print in same line in python

How to Print in the Same Line in Python To print in Python, we use the print () function and the syntax of print () goes like this: print (values, sep =...

3 minutes read.

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.

Python Variables, Constants and Literals

Python is today's most valuable, easy-to-implement and sought-out programming language. Nowadays, developers want to focus on implementing the program rather than spending time with complex programs. So, for this reason,...

17 minutes read.

Augmented reality in python

In this article, we shall learn about augmented reality in python. Augmented reality is a technology that captures the world around you and adds virtual content or objects on top of...

3 minutes read.

Python Rest API

In this tutorial, we will understand the meaning of API and REST API. We will understand the working of REST API. We will then realize the boundaries of architecture defined...

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.

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.

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.

Data Drop in Python

Introduction You'll understand how to delete a group of rows from a Pandas dataframe in this article.You can read this article on How to Drop Columns in Pandas to find out...

6 minutes read.

PyPi TensorFlow

It is a free open-source library for high-performative numerical computations. The architecture of TensorFlow allows us for easy deployment and computing across a varied number of platforms and from desktops...

3 minutes read.

Iterators in Python

Introduction In Python, an iterator is defined as an object that enables traversing through all the values of a collection. It contains the countable number of values. The iterator is utilized to...

4 minutes read.