PY-101 ยท Advanced Python
Generators
โฑ 8 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก The 30-second answer
A generator is a function that uses yield instead of return. Each time you ask for a value it runs until the next yield, hands that value out and pauses, keeping its place for next time. Generators produce huge or endless sequences without storing them all in memory.
- Write a generator with yield
- Use generator expressions
- Know why they save memory
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
def countdown(n):while n > 0:yield nn -= 1yield "Lift off!"for value in countdown(3):print(value)squares = (x * x for x in range(1, 6))print(sum(squares))
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
3
2
1
Lift off!
55 ๐ฏ Write a generator evens(limit) that yields even numbers from 0 up to (not including) limit. print(list(evens(10))) should show [0, 2, 4, 6, 8].
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
for n in range(0, limit, 2): yield n
- The problemYou need the first 10 even numbers that are also multiples of 3 from an endless stream. A list would never finish building. A generator produces them on demand and stops when you do.
- The Python idea
def gen():A generator is a function that uses yield instead of return. - In real lifeAI chat apps stream answers word by word: the model client yields each chunk as it arrives instead of waiting for the full reply.
Start with a question
You need the first 10 even numbers that are also multiples of 3 from an endless stream. A list would never finish building. A generator produces them on demand and stops when you do.
Reading big files, streaming data and AI token streams all use generators so memory stays small.
Explain it like I'm 10
A generator is a storyteller who tells one sentence, then waits for you to say "and then?" before telling the next.
The technical explanation
Calling a generator function does not run it; it returns a generator object.
Each next() runs to the next yield. The function's local variables survive between yields.
(x * x for x in range(10)) is a generator expression: like a list comprehension, but lazy.
Syntax
def gen():
yield value
(expr for x in items) Real-world scenario
AI chat apps stream answers word by word: the model client yields each chunk as it arrives instead of waiting for the full reply.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Next: Decorators โQuestions people ask
What is the difference between yield and return?
return ends a function and sends back one value. yield sends back a value and pauses, so the function can continue and yield more later.
When should I use a generator instead of a list?
When the data is large, endless, or only needed once in order. Use a list when you need indexing, length or several passes.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner What is the difference between yield and return?
return ends a function and sends back one value. yield sends back a value and pauses, so the function can continue and yield more later.
beginner When should I use a generator instead of a list?
When the data is large, endless, or only needed once in order. Use a list when you need indexing, length or several passes.
intermediate Which keyword makes a function a generator?
yield. yield makes it a generator.
intermediate What does calling a generator function return?
A generator object. Nothing runs until you ask for values.
Quick revision
Remember
- Write a generator with yield
- Use generator expressions
- Know why they save memory
- Like iterators, a generator is used up after one pass. Call the generator function again to start over.
Syntax
def gen():
yield value
(expr for x in items) Official documentation
- Generators (docs.python.org)