generator

A function that can pause and resume, producing a series of values one at a time with yield, each only when it is requested.

In more detail

Each time the consumer asks for the next value, the generator runs until its next yield and then pauses. Because values are produced on demand, a generator can walk through a huge file or an endless sequence using almost no memory. In Python any function containing yield is a generator, while in JavaScript generators are written function*. Like any iterator, a generator can be consumed only once.

Examples

The course uses a recursive generator to produce every permutation one at a time.
def countdown(n):
    while n > 0:
        yield n
        n -= 1

Related terms

Taught in

References

Certification courses