Generators

Generators — Functions that return an iterable set of items, one at a time, in a special way.

def infinite_sequence():
    num = 0
    while True:
        yield num
        num += 1
# A simple generator function
def my_gen():
    n = 1
    print('This is printed first')
    # Generator function contains yield statements
    yield n

    n += 1
    print('This is printed second')
    yield n

    n += 1
    print('This is printed at last')
    yield n
  • allow you to declare a function that behaves like an iterator, i.e. it can be used in a for loop.
  • look and act just like regular functions, but use the yield keyword instead of return.
  • Contains one or more yield statements.

Generators — Structure map

Clickable & Draggable!

Generators — Related pages: