Yield Keyword in Python


Introduction

In Python, the “yield” is a type of keyword that is used, when working with the generators. Unlike the normal or the classic functions in Python, where the output or the value is returned using the keyword “return”, the generators use the “yield” keywords for the same.

In this article, we will discuss the yield keyword in Python, what is it, how it works, what is its significance, and its implementation of the same in Python. This article will help one to understand the yield keyword in Python and will help one to use and implement the same whenever necessary.

So let us start discussing the same with the core idea behind yield keywords.

What is Yield Keyword?

In Python, the generators are the type of function, which are mainly used for the iteration processes. As the name suggests, when called, these functions generate the values or the outputs on the fly, meaning that it works like the iterator and generates values continuously, without stopping.

Same as the conventional function in Python, where the return keyword is used to get the output from the function, in the case of generators the yield keyword is used to generate the temporary outputs, where the execution of the generator function is stopped for temporary basis and can be continued later.

In Python, when the generator function is defined to perform certain tasks related to the iteration processes, the next keyword is used, where the outputs or the values are generated continuously and the function keeps on generating the next values. Once the yield keyword is encountered the function stops from there, here the function saves the current state of the generator and then stops.

Note that when the generator function is resumed again or executed again, the values will start generating from where it left off, not from the starting, as the function saves its state when the yield keyword was encountered.

In short, the yield keywords can be thought of as the breaks for the generator keyword, where the generator stops after this keyword and saves its progress, which is not done in normal or conventional functions.

Advantages of Yield Function

There are several advantages that the yield function provides when used with the generator functions. Let us discuss that one by one.

Faster Processes

As we know that generators are the type of function that keeps on generating the values on the fly. With the help of the yield keyword, we can do the operations faster on the generators. It allows the generators to generate the values immediately for even large datasets.

Infinite Outputs

Using the yield keyword with the generators, we can generate the infinite values or the outputs, as it is an iterative process.

Efficiency

As discussed, the yield keywords help in generating the values faster for the generator function. Instead of loading the whole data and then generating the same when requested the yield keyword helps generate and process the same without any loading processes.

Scalable Codes

When writing codes for the iterative processes, there is a very high chance that the codes mess up and are not scalable, The yield keyword for generators helps in writing efficient and scalable codes, which is easy to understand and interpret as well.

Using Yield Keyword: Code Example

Now let us discuss some code examples of implementing the yield function to clear the idea behind the same.

Example 1: Generating the Square of Numbers

Let us try to implement the generator function, where will write a code to get the squares of numbers. As we will be using the generators here, the values will be kept on generating.

# define the generator function to square the numbers
def square_of_numbers(n):
    for i in range(1, n + 1):
        yield i ** 2

# Call the generator function defined above
squares_gen = square_of_numbers(7) #squares of seven numbers will be printed in the output 

for square in squares_gen:
    print(square)

As we can see in the above code example, the function named square generator is defined, which uses the for loop to iterate over the values, and at the end, the yield keyword is used to get the square of the values.

Since we have called the function by passing the 7 as output, the function will give seven different outputs for the square of the respected values.

Output

The output of the following code would be:

1
4
9
16
25
36
49

Example 2: Adding the Strings With Filters

Now let us take an example of the strings. Here we will take the strings as input and will use the generator function with the yield keyword to add the respected strings by applying some filter to the same.

def adding_strings_with_filter(str1, str2):
    for char in str1:
        if char.isalpha(): 
            yield char.upper()
    for char in str2:
        if char.isalpha(): 
            yield char.upper()

# Define the two strings to concatenate

# Also, use the join function to join the strings after applying the filter with the help of generator function

string1 = "TutorialsPoint, is good?"
string2 = "123 for tutorials! 456"
result = "".join(adding_strings_with_filter(string1, string2))

print(result)

Here as we can see in the above code example, we have defined the function named to add a string with filter, which takes two strings as input. Then two loops with the yield keyword are used to get the respected string and at the end of each loop, the yield keyword returns a string with nonalphabetic upper case characters.

In the end, the normal join function is used to add the strings outputs from the generator.

Output

The output from the following code would be:

TUTORIALSPOINTISGOODFORTUTORIALS

Example 3: Generator Function with Custom Logic

Now let us take some unique examples for using the generator and the yield keyword, here we will define a function that will return specific string values for some of the values in the loop.

# defining the generator function
def custom_logic_generator():
    num = 1
    while True:
        if num % 3 == 0:
            yield "divisible by 3" #print divisible by 3
        elif num % 9 == 0:
            yield "divisible by  3" #print divisible by 3
        elif num % 10 == 0:
            yield "divisible by 10" #print divisible by 10

        else:
            yield num
        num += 1

# call the generator function defined above
seq_gen = custom_logic_generator()

# generate the numbers one by list with the above applied logic of the generators
for _ in range(10):
    print(next(seq_gen))

As we can see in the above code example, a function is defined, which prints the values from 1 to 10. Here we have used the yield keyword to define the custom logic. Like, if the number is divisible by 3, then the function will return a “divisible by three” string instead of printing 3 as a numerical value. The same happens with the numbers divisible by 10.

Output

The output of the following code would be:

1
2
divisible by 3
4
5
Divisible by 3
7
8
divisible by 3
divisible by 10

Conclusion

In this article, we discussed the yield keywords in generators, what it is, how it works, and the advantages of the yield keywords and generators, and also discussed two different code examples implementing the same. This article will help one to understand the core idea behind the yield keywords and will help one to apply the same concept to writing efficient codes whenever necessary.

Updated on: 27-Jul-2023

132 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements