Courses/Iterators, Generators & Decorators

Iterators, Generators & Decorators

Generators

Lazy sequences with the yield keyword.

A function that uses yield becomes a generator — it produces values one at a time, only when asked. Great for large or infinite sequences.

def counter():
    n = 0
    while True:
        yield n
        n += 1

c = counter()
print(next(c), next(c), next(c))  # 0 1 2
main.py
Output
Press Run to execute.
Expected output
[1, 4, 9, 16, 25]

Sign in to track your progress across lessons.