Open In App

When to use yield instead of return in Python?

Last Updated : 08 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The yield statement suspends a function’s execution and sends a value back to the caller, but retains enough state to enable the function to resume where it left off. When the function resumes, it continues execution immediately after the last yield run. This allows its code to produce a series of values over time, rather than computing them at once and sending them back like a list.

Let’s see with an example:

Python




# A Simple Python program to demonstrate working
# of yield
 
# A generator function that yields 1 for the first time,
# 2 second time and 3 third time
 
 
def simpleGeneratorFun():
    yield 1
    yield 2
    yield 3
 
 
# Driver code to check above generator function
for value in simpleGeneratorFun():
    print(value)


Output:

1
2
3

Return sends a specified value back to its caller whereas Yield can produce a sequence of values. We should use yield when we want to iterate over a sequence, but don’t want to store the entire sequence in memory. Yield is used in Python generators. A generator function is defined just like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a generator function. 

Python




# A Python program to generate squares from 1
# to 100 using yield and therefore generator
 
# An infinite generator function that prints
# next square number. It starts with 1
 
 
def nextSquare():
    i = 1
 
    # An Infinite loop to generate squares
    while True:
        yield i*i
        i += 1  # Next execution resumes
        # from this point
 
 
# Driver code to test above generator
# function
for num in nextSquare():
    if num > 100:
        break
    print(num)


Output:

1
4
9
16
25
36
49
64
81
100


Previous Article
Next Article

Similar Reads

Difference between Yield and Return in Python
Python Yield It is generally used to convert a regular Python function into a generator. A generator is a special function in Python that returns a generator object to the caller. Since it stores the local variable states, hence overhead of memory allocation is controlled. Example: # Python3 code to demonstrate yield keyword # Use of yield def prin
2 min read
Python Yield And Return In Same Function
Python, a versatile and powerful programming language, offers developers various tools and features to enhance code readability and efficiency. One such feature is the combination of yield and return statements within the same function. In this article, we will explore some commonly used methods where these two statements work together, providing a
3 min read
How to Use Yield Keyword for Memory Efficient Python Code
We are given a task to understand how to use the yield keyword for memory-efficient Python code with the help of different examples with their code. In this article, we will see how to use the yield keyword for memory-efficient Python code. What is the Yield Keyword?The yield keyword in Python is used in the context of generator functions and is fu
4 min read
How to Use __call__() Method Instead of __new__() of a Metaclass in Python?
In Python, metaclasses provide a way to customize class creation. The __new__ and __init__ methods are commonly used in metaclasses, but there's another powerful tool at your disposal: the __call__ method. While __new__ is responsible for creating a new instance of a class, __call__ allows you to control what happens when an instance is called as a
3 min read
Python | yield Keyword
In this article, we will cover the yield keyword in Python. Before starting, let's understand the yield keyword definition. Syntax of the Yield Keyword in Python def gen_func(x): for i in range(x): yield iWhat does the Yield Keyword do? yield keyword is used to create a generator function. A type of function that is memory efficient and can be used
4 min read
Python Yield Multiple Values
In Python, yield is a keyword that plays a very crucial role in the creation of a generator. It is an efficient way to work with a sequence of values. It is a powerful and memory-efficient way of dealing with large values. Unlike a return statement which terminates the function after returning a value, yield produces and passes a series of values.
4 min read
How to Yield Values from List in Python
The yield keyword in Python produces a series of values one at a time and is used with the generator function, it works the same as the return keyword the difference being that the yield keyword produces a sequence of values one at a time. In this article, we will explore different approaches to yield values from a list in Python. Yield Values from
2 min read
Use jsonify() instead of json.dumps() in Flask
Here, we will understand the jsonify() function in the Flask web framework for Python that converts the output of a function to a JSON response object. It is similar to the json.dumps() function in the Python standard library, which converts a Python object to a JSON-formatted string. What is jsonify() The jsonify() function is useful in Flask apps
4 min read
The yield Keyword in Ruby
We can send a block to our method and it can call that block multiple times. This can be done by sending a proc/lambda, but is easier and faster with yield. During a method invocation The yield keyword in corporation with a block allows to pass a set of additional instructions. When yield is called in side a method then method requires a block with
2 min read
Scala | yield Keyword
yield keyword will returns a result after completing of loop iterations. The for loop used buffer internally to store iterated result and when finishing all iterations it yields the ultimate result from that buffer. It doesn't work like imperative loop. The type of the collection that is returned is the same type that we tend to were iterating over
2 min read
Article Tags :
Practice Tags :