← All lessons

Lesson 26

Generators

A function containing yield becomes a generator. Calling it returns an iterator instead of running the whole body.

Each time the loop asks for the next value, the function resumes after the previous yield. Values are produced lazily, so memory stays small.

A generator can be used once. Create a new one to start again.

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

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

Check your understanding

What keyword makes a function a generator?

CHALLENGE

Write a generator evens(limit) that yields even numbers from 2 up to limit. Print list(evens(10)).

Practice →