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