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

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

Last updated on 27th Dec 2021, Blog, General

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) | 19387 Ratings 1025

    Yield in Python can be used like the return statement in a function. When done so, the function instead of returning the output, it returns a generator that can be iterated upon.

    • What is Python yield?
    • Syntax
    • When to use Yield Instead of Return in Python
    • Yield vs. Return
    • What are Generators in Python?
    • Difference between Normal function v/s Generator function.
    • what does the yield keyword do?
    • Use of Yield Keyword
    • Conclusion

    What is Python yield?

    Python yield
    Python yield

      Subscribe For Free Demo

      [custom_views_post_title]

      The yield keyword in Python only works like return with The difference is that instead of returning a value, it returns a generator object to the caller. When a function is called and the thread of execution finds a yield keyword in the function, the function execution stops at that line itself and it returns a generator object to the caller.

      Syntax:-

      yield expression. Description. Python yields a generator object. Generators are special functions that have to be iterated to get values.

      The yield keyword converts the given expression to a generator function that returns a generator object. In order to get the values of the object, yield has to iterate over it reading the given values.

      example: yield methodHere is a simple example of yield. The function tests yield() has a yield keyword with the string “Welcome to the Guru99 Python Tutorial”. When the function is called, the output is printed and it returns a generator object instead of the actual value.

        • def TestField():
        • yield “Welcome to the Guru99 Python Tutorial”
        • output = testField()
        • print (output)

      Output:

        • Generator Object TestField at 0x00000028265EB9A8
        • The given output is a generator object whose value we assigned to yield.
        • But we are not getting the message which we have to give in the output to yield!
        • yield has to iterate over the generator object to print the given message as shown in the example below:
        • def TestField():
        • yield “Welcome to the Guru99 Python Tutorial”
        • output = testField()
        • For I in production:
        • print (i)
        • production

      When to use Yield Instead of Return in Python:-

    • The Python3 yield keyword returns the generator to the caller and the code starts executing only when the generator is iterated.
    • Return to a function is the end of function execution, and a single value is passed back to the caller.
    • Here, that is the case when you should use Yield instead of Return
    • Use yield instead of return when the size of the data is large
    • Yield is the best option when you need to speed up your execution on large data sets
    • Use yield when you want to return a large set of values to the calling function
    • Yield is an efficient way of producing large or infinite data.

      Yield vs. Return:-

      Yield vs. Return
      Yield vs. Return

      Here, are the differences between Yield and Return

      Yield returns a generator object to the caller, and code execution begins only when the generator is iterated. Return to a function is the end of function execution, and a single value is passed back to the caller.

      When the function is called and it encounters the yield keyword, the function execution stops. It returns the generator object to the caller. Function execution will only start when the generator object is executed. When the function is called, execution begins and the value is returned to the caller if there is a return keyword. Return inside a function marks the end of function execution. yield expression return expression

      When the yield keyword is used no memory is used. Memory is allocated for the returned value. Very useful if you have to deal with huge data sizes because memory is not used. Convenient for very small data sizes.

      If yield keyword is used for large data size then performance is better. If the data size is very large then too much memory is used which will hinder the performance. The execution time is faster in terms of yield for larger data sizes. The execution time used is high because if your data size is

      Example: Calling Function with Yield

      In this example we will see how to call a function with yield . In the example below there is a function called test() which returns the square of the given number. There is another function called getSquare() that uses test() with the yield keyword. Output Returns the class value for the given number range.

        • def test(n):
        • return n*n
        • def getSquare(n):
        • For i in the range (n):
        • Yield Test (i)
        • square = gate square(10)
        • For i in class:
        • print (i)
    Course Curriculum

    Develop Your Skills with Advanced Python Certification Training

    Weekday / Weekend BatchesSee Batch Details

      What are Generators in Python?

      Generators are functions that return an iterative generator object. The values from the generator object are fetched at once instead of the whole list at once and hence you can use a for-loop using next() or list() method to get the actual value.

      using generator function You can create a generator by using a generator function and using a generator expression. A generator function is like a normal function, instead of having a return value it will have a yield keyword.

      You need to add a yield keyword to make it a generator function. The following example shows how to create a generator function.

        • def generator():
        • yield “H”
        • yield “e”
        • yield “L”
        • yield “L”
        • yield “o”
        • test = generator()
        • For I in test:
        • print (i)

      Output:

        • h
        • I
        • Took
        • Took
        • hey

      Difference between Normal function v/s Generator function.

      Normal function v/s Generator function
      Normal function v/s Generator function
    • Let us understand how a generator function differs from a normal function.
    • There are 2 functions of general_test() and generator_test().
    • Both functions are supposed to return the string “Hello World”. normal_test() is using return and generator_test() is using yield.
        • # Common Tasks
        • def normal_test():
        • Return to “Hello World”.
        • # generator function
        • def generator_test():
        • yield “hello world”
        • print(common_test()) #call to normal function
        • print(generator_test()) # call the generator function

      Output:

      hello world

      generator object generator_test at 0x00000012F2F5BA20

      The output shows that when you call the normal function normal_test() it returns the string hello world. For generator function with yield keyword it returns generator object generator_test 0x00000012F2F5BA20 and not a string.

      This is the main difference between generator function and normal function. Now to get the value from the generator object we have to either use a loop object or use the next() method or use list().

      print(next(generator_test())) # will output hello world

      Another difference to add to a normal function v/s a generator function is that when you call a normal function the execution will start and stop when it returns and the value is returned to the caller. So when execution starts you cannot interrupt normal function and it will stop only when it comes in return keyword.

      But in case of generator function once execution starts it stops execution and returns generator object when first yield is found. You can use the generator object to get the value and stop and resume as per your requirement.

      what does the yield keyword do?

      Yield is a keyword used to return a value from a function without destroying the state of its local variable. Any function that contains a yield keyword is usually called a generator. When we replace return with yield in a function, it causes the function to hand over the iterator back to its caller, thereby preventing the return function from exiting the function next time. When called, it will start executing from the point where it stopped earlier. And how does this happen? Let’s see that.

      When we use yield keyword to return data from a function, it starts storing the states of local variables, as a result, the overhead of memory allocation for variables in successive calls is saved. Also, since the old state is maintained across successive calls, the flow starts from the last yield statement executed, which, in turn, saves time.

      note: A generator generates values %E2%80%8B%E2%80%8b And cannot be called like a simple function, instead it is called like an iterator, i.e. using a loop, like a for loop. Iterative functions can be made easily by using the yield keyword.

        • # Code to generate cubes from 1 to 300 using the Yield and hence generator
        • >> def cubes(): # an infinite generator function
        • i = 1
        • while true:
        • yield i*i*i
        • i += 1 # next execution starts at this point
        • >> for n in cube():
        • if n > 300:
        • Break
        • print (n)

      Note that the function cubes() is printed until the first yield. Now, if you iterate again, it doesn’t start from the beginning, it starts from where it left off.

      return returns a specific value to its caller function, while yield produces a sequence of values. We should use yield when we need to iterate over the sequence but don’t want to store the whole sequence in memory.

      The yield keyword in Python is not often used or not so well known, but it is of more use if one uses it correctly.

      Use of Yield Keyword

      The yield keyword stops generator function execution and the value of the expression after the yield keyword is returned to the generator’s caller. It can be thought of as a generator-based version of the return keyword.

      yield can only be called directly from the generator function that contains it. It cannot be called from nested functions or callbacks. The yield keyword causes a call to the generator’s next() method to return an IteratorResult object with two properties: value and done. The value property is the result of the evaluation of the yield expression, and is false, indicating that the generator function is not fully completed.

      Once the yield expression has stopped, the code execution of the generator is halted until the generator’s next() method is called. Each time the generator’s next() method is called, the generator resumes execution, and runs until it reaches one of the following:

      A yield, which causes the generator to stop once again and return the new value of the generator. The next time next() is called, execution resumes with the statement immediately following yield.

      Throw is used to throw an exception from a generator. This stops the execution of the generator completely, and resumes execution in the caller (as is usually the case when an exception is thrown).

      The generator function has ended. In this case, the execution of the generator is terminated and an IteratorResult is returned to the caller with the value undefined and done.

      A return statement has been reached. In this case, execution of the generator is terminated and an IteratorResult is returned to the caller containing the value specified by the return statement and done is true.

      If an optional value is passed to the generator’s next() method, that value becomes the value returned by the generator’s current yield operation.

      Between the generator’s code path, its yield operators, and the ability to specify a new initial value by passing it to Generator.prototype.next() , generators provide enormous power and control.

    Python Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

      Conclusion

    • The yield keyword in Python works like return with only one difference: instead of returning a value, it returns the generator function back to the caller.
    • A generator is a special type of iterator that once used will not be available again. Values are not stored in memory and are available only when called.
    • Values from generators can be read using the for-in, list() and next() methods.
    • The main difference between yield and return is that yield returns a generator function to the caller and return returns a single value to the caller.
    • Yield does not store any values in memory, and has the advantage that it is helpful when the size of the data is large, as no values are stored in memory.
    • The performance is better if yield keyword is used than return for large data size.

    Are you looking training with Right Jobs?

    Contact Us

    Popular Courses

    Get Training Quote for Free