Open In App

Python | yield Keyword

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will cover the yield keyword in Python. Before starting, let’s understand the yield keyword definition.

Syntax of the Yield Keyword in Python

def gen_func(x):
    for i in range(x):
        yield i

What does the Yield Keyword do?

yield keyword is used to create a generator function. A type of function that is memory efficient and can be used like an iterator object.

In layman terms, the yield keyword will turn any expression that is given with it into a generator object and return it to the caller. Therefore, you must iterate over the generator object if you wish to obtain the values stored there. we will see the yield python example.

Difference between return and yield Python

The yield keyword in Python is similar to a return statement used for returning values in Python which returns a generator object to the one who calls the function which contains yield, instead of simply returning a value. The main difference between them is, the return statement terminates the execution of the function. Whereas, the yield statement only pauses the execution of the function. Another difference is return statements are never executed. whereas, yield statements are executed when the function resumes its execution.

Advantages of yield:

  • Using yield keyword is highly memory efficient, since the execution happens only when the caller iterates over the object.
  • As the variables states are saved, we can pause and resume from the same point, thus saving time.

Disadvantages of yield: 

  • Sometimes it becomes hard to understand the flow of code due to multiple times of value return from the function generator.
  • Calling of generator functions must be handled properly, else might cause errors in program.

Example 1: Generator functions and yield Keyword in Python

Generator functions behave and look just like normal functions, but with one defining characteristic. Instead of returning data, Python generator functions use the yield keyword. Generators’ main benefit is that they automatically create the functions __iter__() and next (). Generators offer a very tidy technique to produce data that is enormous or limitless.

Python3




def fun_generator():
    yield "Hello world!!"
    yield "Geeksforgeeks"
 
 
obj = fun_generator()
 
print(type(obj))
 
print(next(obj))
print(next(obj))


Output: 

<class 'generator'>
Hello world!!
Geeksforgeeks

Example 2: Generating an Infinite Sequence

Here, we are generating an infinite sequence of numbers with yield, yield returns the number and increments the num by + 1. 

Note: Here we can observe that num+=1 is executed after yield but in the case of a return, no execution takes place after the return keyword.

Python3




def inf_sequence():
    num = 0
    while True:
        yield num
        num += 1
         
for i in inf_sequence():
    print(i, end=" ")


Output:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96.......

Example 3:  Demonstrating yield working with a list.

Here, we are extracting the even number from the list.

Python3




# generator to print even numbers
def print_even(test_list):
    for i in test_list:
        if i % 2 == 0:
            yield i
 
# initializing list
test_list = [1, 4, 5, 6, 7]
 
# printing initial list
print("The original list is : " + str(test_list))
 
# printing even numbers
print("The even numbers in list are : ", end=" ")
for j in print_even(test_list):
    print(j, end=" ")


Output: 

The original list is : [1, 4, 5, 6, 7]
The even numbers in list are :  4 6 

Example 4: Use of yield Keyword as Boolean

The possible practical application is that when handling the last amount of data and searching particulars from it, yield can be used as we don’t need to look up again from start and hence would save time. There can possibly be many applications of yield depending upon the use cases. 

Python3




# func to count number of given word
def print_even(test_string):
    for i in test_string:
        if i == "geeks":
            yield i
 
 
# initializing string
test_string = " There are many geeks around you, \
              geeks are known for teaching other geeks"
 
# count numbers of geeks used in string
count = 0
print("The number of geeks in string is : ", end="")
test_string = test_string.split()
 
for j in print_even(test_string):
    count = count + 1
 
print(count)


Output

The number of geeks in string is: 3

Related Article – 



Last Updated : 17 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads