Thursday, 23 September 2021

Python: Generators, yield demo

Generators are used to implement iterators effectively. Generator is a simple function with yield keyword used inside. Yield keyword is used to get the next item in the iterator.

 

return vs yield

‘return’ statement is used to come out of the function, whereas yield keyword pause the function by saving its internal state.

 

Let’s see it with an example.

def send_messge():
    yield 'Hello'
    yield 'Hi'
    yield 'are you there'

  Now, we can use next() function to retrieve the next yield item from the function.

 

state = send_messge()
print (next(state))

 

Above statement return the first yield., if you call ‘print (next(state))’ method again, it will return next yield value etc.,

 

generator_demo.py

 

def send_messge():
    yield 'Hello'
    yield 'Hi'
    yield 'are you there'

state = send_messge()

# yields the result of first yield statement
print (next(state))

# yields the result of second yield statement
print (next(state))

# yields the result of third yield statement
print (next(state))

Output

Hello
Hi
are you there


Let’s add some more log statement to better understand the behavior.

 

generator_demo.py

def send_messge():
    print('about to yield "Hello"')
    yield 'Hello'

    print('about to yield "Hi"')
    yield 'Hi'

    print('about to yield "are you there"')
    yield 'are you there'

state = send_messge()

# yields the result of first yield statement
print('calling the next method first time')
print (next(state))

# yields the result of second yield statement
print('\ncalling the next method second time')
print (next(state))

# yields the result of third yield statement
print('\ncalling the next method third time')
print (next(state))


Output

calling the next method first time
about to yield "Hello"
Hello

calling the next method second time
about to yield "Hi"
Hi

calling the next method third time
about to yield "are you there"
are you there


Let me explain one more example, where I am going to define a generator that yield odd numbers.

 

odd_number_generator.py

def odd_number_gen(max_number):
    count = 1

    while count < max_number:
        yield count

        count += 2

try:
    state = odd_number_gen(10)
    while True:
        print(next(state))
except StopIteration:
    pass


Output

1
3
5
7
9



Previous                                                    Next                                                    Home

No comments:

Post a Comment