Generator (Python)

A generator hands out a sequence of values one at a time, as they are asked for, instead of building a whole list in memory at once. Calling a function that uses yield makes one. It is memory-efficient for large or infinite sequences.

Python

Each time you ask a generator for the next value, it runs until the next yield, hands back that value, and pauses — remembering where it left off. You loop over a generator like any other iterable.

Examples

Python

def count_up(n):
    i = 0
    while i < n:
        yield i
        i += 1

for x in count_up(3):
    print(x)

Output:

0
1
2

Learn it in a lesson

See also

Back to the Dictionary