How to Understand the “Yield” Keyword in Python

In programming, oftentimes a large amount of information is to be retrieved and returned back to the caller function by the user. The yield keyword can help in this situation as it can handle big data efficiently and is comparatively faster than return when creating an infinite sequence of numbers.

This article provides use cases, differences between the “return” and “yield” keywords, and the advantages and disadvantages of using the “yield” keyword. It also gives examples to illustrate these concepts.

How to Understand the “Yield” Keyword in Python?

The yield keyword/statement produces a generator object. It retrieves any information provided with the yield keyword and gives that information to the caller. The generator function can be treated as an iterator object. To get the desired output, the function generator should be iterated over to get the information from the function generator.

Syntax:

def gen_nums(lim):
    for num in range(lim):
        yield num
  • gen_nums is the name of a user-defined function that takes the parameter lim.
  • lim represents the maximum limit depending on which the generator will yield the values.
  • The for-loop check for each number(num) within the specified range.
  • The yield keyword yields each number in the range.

Example 1: Yield Keyword and Generator Object

Generator functions have one specific characteristic: they utilize the yield keyword rather than giving back data. Functions like “__iter__()” and “next()” are automatically created while using functions. Data can be created in huge amounts with the help of generators. Here is a code that defines a function generator and how we can generate data from it:

def fun_gen():
yield "I like to code in Python"
yield "Python Tutorial"
yield "Coding solves problems!"
obj = fun_gen()
print(type(obj))
print(next(obj))
print(next(obj))
print(next(obj))

In the above code,

  • A function generator func_gen is defined and called.
  • Next, three statements are given along with the yield keywords that contain different strings.
  • “obj=fun_gen()” creates a generator object named “obj” while calling the “func_gen()” function. The yield statement is executed when the “next(obj)” is called.
  • print(type(obj)) will print the type of the object which will be the <class ‘generator’> confirming that obj is a generator object.
  • print(next(obj)) executes the next value from the generator until it finds the yield keyword. Then it returns the value provided in the first yield. If called again, the information in the second yield will be retrieved. This goes on and on until no more yield keywords are found. Then the interactions will stop.

Output

The following output shows how data can be retrieved using the yield keyword:

Example 2: Creating an Infinite Series 

An infinite series can be created using the yield keyword. In this example, an infinite series of numbers is created where yield gives back the number while adding each number by 1. A number is added after the execution of the yield keyword but considering return, no execution will occur unless the code reaches the return keyword. The code below shows how an infinite series can be created using the yield keyword:

def inf_seq():
numb = 0
while True:
yield numb
numb += 1

for n in inf_seq():
print(n, end=" ")

In the above code,

  • A function inf_seq()l generates a never-ending progression of integers.
  • numb indicates a number and is initialized as 0 outside the infinite loop.
  • While the statement is true, yield will give back the current value of num as the generator’s output. The function’s execution is stopped, and the value is provided to the for loop every time the function is called.
  • After the yield is executed, numb is incremented by 1.
  • The for loop iterates over the inf_seq() generator and prints the yielded value.
  • As end= “ ” which means there is no condition provided to terminate the loop. The loop will keep running continuously.

Output:

The following output shows an infinite sequence of numbers created using the yield keyword:

Example 3: How to Utilize the Yield Keyword as a Boolean

One use case of the yield keyword is to find something specific from a large amount of data. The yield keyword is utilized which saves time from searching it from scratch. Here is a code that displays how we can find the frequency of the string “shells” in a famous tongue twister:

def find_pasta(tst_str):
 for i in tst_str:
 if i == "pasta":
  yield i
tst_str = " I want penne pasta Arabian pasta and Alfredo pasta"
c = 0
print("The number of pasta in the provided string is : ", end="")
tst_str = tst_str.split()
for j in find_pasta(tst_str):
 c = c + 1
print(c)

In the above code,

  • A function generator, find_pasta() is defined that takes the parameter tst_str. It is known the occurrence of pasta in the provided string.
  • The main execution block contains the split() function. It iterates over the generator function find_pasta()
  • c=0 initializes the count that counts the number of times pasta will appear in the tongue twister. The original value will be 0.
  • The counter c is incremented for each occurrence of the word pasta.
  • The final count is printed which is 3.

Output

The following output displays how certain data can be retrieved from a longer piece of information using the yield keyword:

Example 4: How to Use the Yield Keyword Inside a List

In this example, the list contains the yield functionality. The following code shows how the yield statement can be executed inside a list:

def gen_odd(numbers):
  for num in numbers:
        if num % 2 != 0:
            yield num
tlist = [8,9,0,2,5,7,8,88,55,33,63,95]
print("The initial list is:", tlist)
odd_numbers = gen_odd(tlist)
print("The odd numbers in the given list are:", *odd_numbers)

In the above code,

  • A function generator gen_odd is defined with the parameter “numbers” and yields odd numbers.
  • Inside the function, the for loop iterates over each number provided in tlist.
  • For each number, it checks the condition “num % 2 != 0”. If it is not divisible by 0, it means the number will be odd and the yield will give back the odd number.
  • A test list tlist contains different integers, including odd and even.
  • The original list is printed and the gen_odd function is called on the test list that will generate the odd numbers provided in the list.
  • The print function will print the odd numbers inside the list.

Output

The following output shows the usage of the yield keyword inside a list where we have extracted the odd numbers from a list:

Comparison of Yield and Return in Python

The key difference between the yield and return keywords is that when using the return function, there is no further execution of the function and the value is returned. However, the yield statement stops the execution for a while only. Return statements do not get executed no matter what, while the yield statements are executed when the function continues its operation.

Pros and Cons of the Yield Function

ProsCons
It is good for efficient memory as it is only executed when the caller is operating on the object.The code flow is difficult to understand as the function generator returns numerous values.
It saves us time as we can resume and stop from a similar place due to the saving of the variable states.Not calling the generator functions properly might cause problems.

Conclusion 

The yield keyword in Python controls the flow of the generator function and returns the data while pausing the execution of the function for a while. While the execution is stopped, a generator function object is returned. It will be returned to the caller. This article discusses the yield keyword, and its use cases, and explains it with the help of examples.