How To Use Yield In Python?


In this article, I will explain what the yield keyword is and how to use it in Python.


Python is an interpreted, high-level, general-purpose programming language created by Guido van Rossum and first released in 1991. He started Python as a hobby project to keep him occupied in the week around Christmas. It got its name from the name of the British comedy troupe Monty Python. It is used in:

  1. Software Development
  2. Web Development
  3. System Scripting
  4. Mathematics

To learn how to program in Python, visit Python Basics.

You can visit C# Corner Python Learn Series.

Python Decorators 

A decorator is a Python design pattern that allows a user to add additional functionality to an existing object without changing its structure. Decorators are often summoned prior to the specification of the function to be decorated. These are used to alter the function's behavior. Decorators allow you to wrap another function in order to extend the functionality of the wrapped function without permanently changing it.

To know more, visit.

Python Yield Keyword

The yield statement suspends the function's execution and returns a value to the caller while retaining enough state to allow the function to restart where it left off. When the function is resumed, it begins execution immediately after the last yield run. This enables its code to generate a succession of values over time, rather than computing them all at once and returning them as a list.

In other words, Yield is used to return from a function without deleting the states of its local variables. When the function is invoked, execution begins at the last yield statement. A generator is any function that contains the yield keyword. As a result, yield is what distinguishes a generator.

Benefits of Yield

  • Because it saves the local variable states, memory allocation overhead is kept to a minimum.
  • Because the former state is kept, the flow does not start from the beginning, saving time.

Disadvantages of Yield

  • If the function call is not handled correctly, the usage of yield might become erroneous.
  • Time and memory optimization come at the expense of code complexity, making it difficult to comprehend the rationale behind it at times.

When to use Yield in Python

  1. When the size of the returned data is enormous, you can use yield instead of putting it in a list.
  2. Yield is a preferable alternative if you require faster execution or calculation over huge datasets.
  3. You may decrease memory use by using yield.
  4. It can generate an unending stream of data. You may set the size of a list to infinite, however, this may result in a memory limit problem.
  5. If you wish to make continuous calls to a function that has a yield statement, it will start from the last defined yield statement, which will save you a lot of time.

Python Yield vs Python Return

Yield is commonly used to turn an ordinary Python function into a generator. Return is commonly used to indicate the conclusion of execution and "returns" the result to the calling statement.
It replaces a function's return to halt execution without losing local variables. It quits a function and returns a value to its caller.
When the generator provides an intermediate result to the caller, this method is utilized. It is used to indicate that a function is ready to submit a value.
Code is written after the yield statement in the next function call is executed. Code introduced after the return statement will not be executed; instead, it will be ignored.
It has the ability to run many times. It is only activated once.
The yield statement function is called from the function's final state before it is interrupted. Every function calls to start the function from the beginning.
When the yield keyword is used, no memory is consumed. Memory is set aside for the returned value.
When dealing with big amounts of data, using the yield keyword improves speed. If the data size is large, a lot of memory is consumed, which slows down speed.
In the case of yield for huge data volumes, execution time is reduced. The execution time is long since there is more processing done if your data size is large; nonetheless, it will function properly for minor data sizes.
def generator_test():
yield "Hello World"


Output: <generator object generator_test at 0x00000012F2F5BA20>

def normal_test():
return "Hello World"


Output: Hello World


Yield Examples

Following are some code examples to demonstrate how we can use Yield Keyword in Python.

1. Fibonacci Series

def Fib(num):
    c1, c2 = 0, 1
    count = 0
    while count < num:
        yield c1
        c3 = c1 + c2
        c1 = c2
        c2 = c3
        count += 1

for i in Fib(7):

In the above code, we are using yield to return the value of c1, which is then passed to Fib(7) function call. The output of the above code will be 0 1 1 2 3 5 8

2. Calling a function using Yield

def test(n):
    return n*n

def getSquare(n):
    for i in range(n):
        yield test(i)

sq = getSquare(10)

for i in sq:

In the above code, we are calling test using yield. The output will be: 0 1 4 9 16 25 36 49 64 81.

3. Using Nested Generators

def gen_int(n):
    for i in range(n):
        yield i

def gen_2(gen):
    for n in gen:
        if n % 2:
            yield n

for i in gen_2(gen_int(10)):

In the above code, we are calling gen_int from gen_2, hence nesting the yield result. The output will be: 1 3 5 7 9

4. Reading file using Yield

def fr(name):
    for row in open(name, "r"):
        yield row

gen = fr("file.txt")
row_count = 0

for row in gen:
    count += 1

print(f"Row count is {count}")

In the above code, we have opened the file in reading mode, and we are using yield to return the file contents.


In this article, we discussed what Python Yield keywords are and how we can use them in Python. Do try out the code and make tweets to enhance your understanding, and comment with your views on how useful this article was.

Visit C# Corner to find answers to more such questions.

If you have any questions regarding any other technology do have a look at the C# Corner Technology Page.

C# Corner
MVP Program Director