Site icon i2tutorials

Python -Yield Keyword

When we write a function, we normally use the return statement for returning the result from a function.

The yield keyword in python is also just like return which is used to return a value from a function but this keyword also maintains the state of the local variables of the function and the execution starts from the yield statement executed previously when the function is called again.

Let’s look at an example to understand what about yield keyword:

 

Example:

 

# generator to print odd numbers
def print_odd(x_list):
  for i in x_list:
    if i % 2 != 0:
        yield i

# initializing list 
x_list = [1, 4, 5, 6, 7, 8, 12]

# printing initial list
print ("The original list is : " +  str(x_list))

# printing odd numbers 
print ("The odd numbers in list are : ", end = " ")
for j in print_odd(x_list):
  print (j, end = " ")

 

Output:

 

 

In the code above we have defined a simple function which has a condition for finding the odd value and yielding the odd value of i.

When a yield statement is used in a function then it is called as Generator.

 

Advantages of yield:

 

 

Disadvantages of yield:

 

 

Exit mobile version