Python Tutorial 0/52 lessons ~6 min read Lesson 16
Generators & yield
Generators produce values lazily using yield — memory-efficient for streams, large files, and infinite sequences.
Course progress0%
Focus
9 guided sections
Practice signal
Examples included
Career prep
Interview Q&A included
Introduction
Generators produce values lazily using yield — memory-efficient for streams, large files, and infinite sequences.
Understanding the topic
Core concepts to understand:
yieldpauses the function, returns a value.- Generator expressions:
(x*2 for x in xs). next()advances; loops iterate.yield fromdelegates to another generator.
Syntax reference
Visual flow / code:
python
def count_up(limit: int):n = 0while n < limit:yield nn += 1for x in count_up(5):print(x) # 0..4# Generator expression — memory-efficienttotal = sum(x * x for x in range(1_000_000))# Stream a huge file line by linedef read_lines(path):with open(path) as f:for line in f:yield line.strip()
Execution workflow
1Generators & yield Workflow
1 / 4yield pauses the function, returns…
yield pauses the function, returns a value.
Real-world use
Generators are how Python handles 50-GB log files without loading them into memory. ETL pipelines, web crawlers, and data streams all rely on them.
Best practices
- Use generators for any sequence > a few thousand items.
- Combine with
itertoolsfor power. - Prefer generator expressions to list comps when iterating once.
Common mistakes
- Generators are single-use — exhausted after iteration.
- Cannot index a generator (
g[0]fails).
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionyield vs return?+
Answer
return ends a function and gives back one value, discarding its local state. yield suspends the function, hands a value to the caller, and keeps its state so it resumes on the next next() call. A function containing yield is a generator function, and calling it returns a generator object without running the body yet.Follow-up
What does a return statement do inside a generator?
2BeginnerQuestionGenerator vs list — memory?+
Answer
A list holds all its elements in memory at once, so memory grows with size, while a generator produces one item at a time and keeps only its current frame state. This makes generators suitable for large or unbounded streams. The trade-off is that a generator is single-use and does not support indexing,
len, or random access.3IntermediateQuestionWhat's lazy evaluation?+
Answer
Lazy evaluation means a value is computed only when it is needed rather than up front. Generators,
range, map, filter, zip, and file iterators are lazy in Python 3, so a pipeline processes one item at a time. It saves memory and allows infinite sequences, but errors and side effects appear later, at consumption time.Follow-up
What is a downside of lazy evaluation when debugging?
Summary
In summary: Lazy, memory-efficient sequences. yield = pause + emit.
Ready to mark this lesson complete?Track your journey across the entire course.