What is yield in python LEARNOVITA

What does the Yield keyword do and How to use Yield in python ? [ OverView ]

Last updated on 03rd Nov 2022, Artciles, Blog

About author

Nirvi (Python developer )

Nirvi is a Python developer with 7+ years of experience in the Hadoop ecosystem, Sqoop, Hive, Spark, Scala, HBase, MapReduce, and NoSQL databases, such as HBase, Cassandra, and MongoDB. She spends most of her time researching technology and startups.

(5.0) | 18574 Ratings 2146
    • In this article you will get
    • 1.What is Yield In Python?
    • 2.Generator functions in Python
    • 3.Example of using a yield In Python (Fibonacci Series)
    • 4.How can you call functions using Yield?
    • 5.Why and When Should you use Yield?
    • 6.Yield Vs. Return In Python
    • 7.Advantages and Disadvantages of Yield
    • 8.Conclusion

What is Yield In Python?

The Yield keyword in a Python is similar to the return statement used for returning values or objects in a Python. However, there is a slight difference. The yield statement returns the generator object to the one who calls a function which contains yield, instead of simply returning a value.

Inside the program, when you call a function that has yield statement, as soon as a yield is be encountered, the execution of a function stops and returns an object of a generator to function caller. In simpler words, a yield keyword will convert an expression that is specified along with it to the generator object and return it to a caller. Hence, if need to get a values stored inside generator object, need to iterate over it.

It will not destroy a local variables’ states.. Please note that a function that contains the yield keyword is known as generator function. When use a function with the return value, every time call the function, it starts with the new set of variables. In contrast, if use a generator function instead of normal function, an execution will start right from where it be left last.If need to return a multiple values from a function, can use a generator functions with yield keywords. The yield expressions are return multiple values. They return a one value, then wait, save a local state, and resume again.

Generator functions in Python

In Python, a generator functions are those functions that, instead of a returning a single value, return an iterable generator object. can access or read values returned from a generator function stored inside a generator object one-by-one using the simple loop or using next() or list() methods.

Can create a generator function using a generator() and yield keywords. Consider an example below.

  • def generator():
  • yield “Welcome”
  • yield “to”
  • yield “Earth”
  • gen_object = generator()
  • print(type(gen_object))
  • for i in gen_object:
  • print(i)

In above program, have created a simple generator function and used a multiple yield statements to return the multiple values, which are stored inside generator object when create it. can then loop over an object to print values stored inside it.

Generator functions

Example of using a yield In Python (Fibonacci Series)

Here is the general example that you can use to understand concept of yield in the most precise manner. Here is the Fibonacci program that has been created using a yield keyword instead of return.

  • def fibonacci(n):
  • temp1, temp2 = 0, 1
  • total = 0
  • while total < n:
  • yield temp1
  • temp3 = temp1 + temp2
  • temp1 = temp2
  • temp2 = temp3
  • total += 1
  • fib_object = fibonacci(20)
  • print(list(fib_object))

Here, have created Fibonacci program that returns a top 20 Fibonacci numbers. Instead of storing an each number in an array or list and then returning the list, have used yield method to store it in an object which saves ton of memory, especially when a range is large.

Example of yield function

How can you call functions using Yield?

Instead of a return values using yield, can also call functions. For example, suppose have a function called cubes which takes the input number and cubes it, and there exists the another function that uses a yield statement to create a cubes of a range of numbers. In such a case, can use cubes function along with yield statement to create a simple program.

  • def cubes(number):
  • return number*number*number
  • def getCubes(range_of_nums):
  • for i in range(range_of_nums):
  • yield cubes(i)
  • cube_object = getCubes(5)
  • print(list(cube_object))

Why and When Should you use Yield?

When use yield keyword inside a generator function, it returns a generator object instead of a values. In fact, it saves all the returned values inside this generator object in the local state. If have used a return statement, which returned an array of values, this would have consumed the lot of memory. Hence, yield should always be a preferred over a return in such cases.

Moreover, an execution of the generator function starts only when caller iterates over a generator object. Hence, it increases overall efficiency of the program along with the decreasing memory consumption. Some situations where should use yield are:

    1. 1.When a size of returned data is quite big, instead of storing them into a list and can use yield.
    2. 2.If need faster execution or computation over large datasets, yield is the better option.
    3. 3.If need to reduce memory consumption, can use a yield.
    4. 4.It can be used to produce the infinite stream of data. Can set as size of a list to infinite, as it might cause memory limit error.
    5. 5. If need to make continuous calls to a function that contains the yield statement, it starts from a last defined yield statement, and hence, can save a lot of time.

Advantages and Disadvantages of Yield

The advantages of using yield keywords instead of a return are that are values returned by a yield statement are stored as local variables states, which allows control over a memory overhead allocation. Also, every time, the execution does not start from beginning, since a previous state is retained.

However, a disadvantage of yield is that, if calling of functions is not be handled properly, the yield statements might sometimes cause an errors in the program. Also, when try to use a yield statements to improve the time and space complexities, an overall complexity of the code increases which makes it complex to understand.


Explored how can leverage a yield in Python to optimize programs in terms of the both speed and memory saw several examples of a generator unctions and the various scenarios where can use a yield statements. Moreover, also explored why and when should you use it, along with its advantages and disadvantages.

Are you looking training with Right Jobs?

Contact Us

Popular Courses