How to Use Generators in Python


In Python, a function used for yield is called a generator.

  • Unlike ordinary functions, the generator is a function that returns an iterator. It can only be used for iterative operations.
  • During the execution of the generator, each time the yield is encountered, the function pauses to return yield value and then continues to run from the pause position.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

import sys

def fibonacci(n):  # Generator function - Fibonacci
    a, b, counter = 0, 1, 0
    while True:
        if (counter > n):
            return
        yield a
        a, b = b, a + b
        counter += 1

f = fibonacci(10)  # f is an iterator that is generated by the generator

while True:  # print out values in the iterator
    try:
        print(next(f), end=" ")
    except StopIteration:
        sys.exit()

Output:

0 1 1 2 3 5 8 13 21 34 55  

Tips

  • Equivalent to encapsulating iter and next for functions.
  • yield can return multiple values in the loop. In contrast, return command can only return once and then the loop is terminated.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments