Home » Yield Keyword in Python

Yield Keyword in Python

by Online Tutorials Library

Yield Keywords in Python

Python includes many tools that vastly simplify the life of programmers. One such tool is the yield keyword in Python. We can use this keyword in place of return statements in regular Python procedures. We will learn about the yield keyword, its application in generator functions, the difference between a return statement and a yield statement, and when we can replace a return statement with a yield statement.

What is the Yield Keyword in Python?

The yield keyword of Python is comparable to another keyword called return, which we use to return an expression or object, usually in functions. There is, although, a little variation. Instead of just returning a value to the call of the function that includes the yield statement, the yield statement of a function returns a generator object.

When we call a function in the program with a yield statement, the function’s execution suspends when the Python interpreter encounters a yield statement. The caller receives an object from the generator class. To put it another way, the yield keyword will transform any expression supplied with it into a generator object and then return that generator object to the caller. Therefore, we must iterate through the generator object to obtain the values.

Please be aware that a function using the term yield is called a generator function. The yield keyword won’t ruin the states of the local variables. The latest yield expression will be used as the starting point for the execution every time a function is called.

Every time we call a function with a return statement, a fresh set of variables is introduced. The function’s execution will resume where it left off if a generator function is used in place of a regular function.

We can use the combination of generator function and yield keyword to return multiples function through a function. The yield expression returns multiple values. They return a single value, pause the execution, save the current local state of the variable declared, and then continue.

Syntax of the yield Keyword in Python

Brief on Generator Functions in Python

Generator functions in Python are those that, unlike the regular functions that return a single expression, return an iterable object, which we call a generator object. Using a basic Python loop, or the methods like the next() or list(), or the variables stored within a generator object one at a time, we can approach or read the values from the generator function. We created a generator function using the def keyword. A good example is provided below.

Example of yield Keyword with a Generator Function

We will print certain strings when we call the functions.

Code

Output:

<class 'generator'>  Yield  Keyword  in  Python  

In the program mentioned above, we made a basic generator function, and after using several yield expressions to return several values, Python then saved within a generator object we made. The values inside this generator function can then be displayed on the console using a loop over the object.

Filtering Odd Numbers Using yield Keywords

Let’s build a new generator function that uses the yield keyword. We’ll attempt to eliminate every odd number from a list of integers. Additionally, it is crucial in this situation to output the information held inside the generator object using various methods like list(), for-in, and next().

Look at the example below.

Code

Output:

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33]  

How to Call Functions which have yield?

We can call functions in place of returning values with yield. Imagine, for instance; we define a function square() which returns the square of a number given to it on execution. This code has a return keyword. There is one more function square() with a yield keyword to give squares of a range of values. In this situation, we may develop a straightforward program by combining the yield expression with the square() function. Examine the example code in the section below.

Code

Output:

[0, 1, 4, 9, 16, 25, 36, 49]  

How return Keyword is Different from yield Keyword

The Python Yield keyword works similarly to the return keyword used for values, except that rather than only providing a value in return of the function, the generator function that includes the yield keyword inside it returns a generator object. Their key distinction is the return keyword of Python returns the value, which stops the function’s execution. The yield keyword, however, delays the function’s execution. Statements after return keywords are never performed, which is another distinction. When the function continues its execution, yield statements are carried out.

When should One Use yield Instead of return Keywords?

The yield keyword pauses the function’s execution and returns a value while keeping a sufficient state for the generator function to pick up from where yield paused it. When execution is continued, the function starts again right where the previous yield execution ended. Instead of calculating values simultaneously and returning them as a list data type in output, this enables its program to output a succession of values throughout time.

Advantages of Using yield:

  • Memory allocation load is kept within check because it retains local variable states.
  • Because the former state is kept, the process doesn’t have to start over, which reduces time.

Disadvantages of Using yield:

  • We need to call the function correctly. Otherwise, using yield can occasionally become incorrect.
  • Coding complexity increases due to time and storage optimization, making the reasoning behind it occasionally difficult to comprehend.

Let us look at an illustrative example:

Code

Output:

Function with return keyword:  3.0  Function with yield keyword:  [0.0, 1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.23606797749979, 2.449489742783178, 2.6457513110645907, 2.8284271247461903]  

While yield might generate a series of results, the return keyword returns a specific value to its caller. If we want to iterate through a series but don’t want to keep the complete series in memory, we must use yield.

Python generator functions use yield return output. When a generator function is defined using the def keyword, and it has to create a value, it uses the yield keyword instead of the return keyword. When the yield is included in a def’s body, the function transforms into a generator function.

List of Differences between yield Keywords and return Keywords

Here are a few distinctions between Python yield and return.

Point of Difference Yield Keyword Return Keyword
Definition When we call a generator function, it creates a generator object by combining all the values returned by the yield keyword. Additionally, code begins to run only after the caller iterates through the object. The function execution ends as soon as it hits the return statement, returning just one value to us.
Function The initial yield is executed, and the function terminates when we call the generator function. The generator object, which contains the value given by yield, is then returned to us. The subsequent yield statement is then executed, and the cycle is repeated when we have to access or iterate over this variable. A regular function’s execution starts when we call it and finishes when it has reached the return statement. The value is then returned to us.
Number of Keywords per Function In a generator function, we can use many yield statements. In a typical function, we can use just one return statement.
Storage When using yield keywords, no storage space is allocated. Memory is allotted for every returned value.
Application Exceptionally memory-efficient, particularly when working with huge data sets. We should use this keyword on smaller data sets.
Execution Using the yield keyword speeds up execution times for huge data sets. Larger data sizes result in longer execution times because additional computation is required.

You may also like