Fork me on GitHub

One application of yield

When you want to generate an iterable letter list such as ['A', 'B', ..., 'J'], using yield will be very graceful.
An example is listed below:

def letter_increment(letter):
    assert len(letter) == 1
    return chr(ord(letter) + 1)

def iter_letter(start_letter='A', end_letter='J'):
    current_letter = start_letter
    while True:
        yield current_letter
        if current_letter == end_letter:
            raise StopIteration
        current_letter = letter_increment(current_letter)

In this way, you can write:

for letter in iter_letter('A', 'J'):
    print(letter)

Then you'll get results like this:

'A'  
'B'  
'C'  
...  
'J'

Also, you can implement an iterator class which is kind of heavy.

In the essence, the for in statement in Python is the wrapper of an iterator. It generates an iterator and call the next() method in every loop. In the end, it also handles the StopIteration exception automatically to stop the iteration.

links

social