← Python Intermediate
13 / 25
Lesson 13 — Generators
Lazy sequences
A function with yield is a generator. Each call to next() runs it until the next yield, hands out that value, and pauses right there. The next call continues from the same spot, so local variables keep their values.
def countdown(n):
while n > 0:
yield n
n -= 1
Why it matters: generators produce values one at a time, so they handle huge or even endless sequences without filling memory.
Want it another way?
Task
Make evens() yield 0, 2, 4, ... so the first 5 values print as [0, 2, 4, 6, 8].
Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.
Test your knowledge
A quick 3-question quiz on this lesson — instant feedback.