Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • yield in python

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 630
    Comment on it

    yield in python

    The yield statement in python is similar to return statement, the only difference is that whenever yield statement is encountered in a function, the execution of function is suspended and a value is send back to the caller but because of yield whenever the function is called again, the execution of function begin where it left off previously. When resumed, the function continues execution immediately after the last yield run. Thus yield allows a function to produce a series of values over time, instead of computing them at once and sending them back all at once like a list. Yield produces a sequence of values and are used in generator function.   

    Example of yield in python:-

    # A generator function that yields 1 for first time,
    # 2 second time and 3 third time
    def simpleGeneratorFun():
        yield 1
        yield 2
        yield 3
     
    # Driver code to check above generator function
    for value in simpleGeneratorFun(): 
        print(value)

    Output:

    1
    2
    3

    In above program output is 1,2,3 because when for loop run over simpleGeneratorFun(), simpleGeneratorFun() is called and within that function first yield is encountered therefore returning 1, again when loop runs, function resumes execution immediately after the last yield run therefore returning 2 and so on.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: