Yield in Python

Yield in Python Tutorial

Table of Contents

While working with a large amount of data the programmer sometimes needs to control the function’s start and stop state. The Yield gives the programmer the power to execute the program the way he/she wants rather than computing them at once. Let’s take a look at an example. Suppose you have a function that prints “Hello World” 5 times and functions that Yields “Hello World” five times. Let’s take a look at the difference between Yield and simple return for Yield in Python.

def normal():
print("Hello World")
print("Hello World")
print("Hello World")
print("Hello World")
print("Hello World")
def yielding():
yield "Hello World"
yield "Hello World"
yield "Hello World"
yield "Hello World"
yield "Hello World"

normal()
print("Now Calling Yeilding function")
print(yielding())
Yield in Python

Take a look at the above output. The normal function gives us back 5 print statements but the yielding function gives a generator.

Now we need to loop over the generator to get the output.

def yielding():
yield "Hello World"
yield "Hello World"
yield "Hello World"
yield "Hello World"
yield "Hello World"

print("Now Calling Yeilding function")
output = yielding()
for i in output:
print(i)
yield Hello World

How to read the values from the generator?

Let’s take a look at different ways to read values from generators.

Using : list()

We can use the list function to generate all the output and store it in a list.

def even_num(x):
for i in range(x):
  if (i%3==0):
      yield i
num = even_num(20)
print(num)
print(list(num))
Yield in Python Tutorial

Using : for-loop

In Yield in Python, We used for loop to iterate over the generator in the first example. Let’s take another example.

def even_num(x):
for i in range(x):
  if (i%3==0):
      yield i
num = even_num(20)
print(num)
for i in num:
print(i)
yield Hello World

Using next()

There is a built-in function next which is used to generate the next number from generator. After generating the last item it will give an error. 

def even_num(x):
for i in range(x):
  if (i%3==0):
      yield i
num = even_num(10)
print(num)
print(next(num))
print(next(num))
print(next(num))
print(next(num))
print(next(num))
Yield in Python Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share this article
Subscribe
By pressing the Subscribe button, you confirm that you have read our Privacy Policy.
Need a Free Demo Class?
Join H2K Infosys IT Online Training
Enroll Free demo class