Skip to main content

Python: yield Keyword

In Python, the yield is a keyword that is used in Python to return some value from the function without finishing the states of a local variable. It means it stores all the states of the variable inside a function and later starts executing of the function from the last yield statement. 

Syntax:

def fun():  
    yield expression 
    print(fun)

Advantage of Yield:

  • It is the best statement used in the generator function to store a local variable's states and resume its execution from the last yield statement.
  • Since the old state is retained, the flow doesn’t start from the beginning and hence saves time.

Disadvantage of Yield Keyword:

  • Time and memory optimization of the code complexity, and sometimes it is hard to understand the yield statement's working logic.

Example: 

def func_1():  
    yield "Welcome to the Python"    

result = func_1()  
for x in result:
    print(x)

Output: Welcome to the Python

Tags
Submitted by devanshi.srivastava on July 8, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.