Python – yield – simple explanation

Meaning of this post is to create first simple understanding of the yield. Yield is one of the topics that maybe hard to understand in the Python.

Short explanation: Yield can pause a function and return current result.

So yield works almost as return in the function. How to get value and resume function? First way to get current value and resume function by for loop:

#!/usr/bin/env python3

def characters():
    yield 'a'               # pause the function and return result
    yield 'b'               # pause the function and return result
    yield 'c'               # pause the function and return result
    yield 'd'               # pause the function and return result
    yield 'e'               # pause the function and return result

for item in characters():   # get current value and resume function
        print(item)

Output

a
b
c
d
e

Second example how to continue paused function by next() method. next() method returns value as well:

#!/usr/bin/env python3

def characters():
    abc = [ 'a', 'b', 'c', 'd', 'e' ]
    for x in abc:
        yield x             # pause the function and return result

generator = characters()    # assign generator

print( next(generator) )    # get current value and resume function
print( next(generator) )    # get current value and resume function
print( next(generator) )    # get current value and resume function

Output:

a
b
c

Each next(generator) returns value and resume function until next yield.

Can you do the same without yield? Yes

Why I need yield?

  • Another way to write simple and efficient code (no extra objects).
  • Getting data from infinite loops.

Understanding of Iterators and Generators is needed to understand how yield working. But I avoided them to make explanation simple.

Leave a Reply

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