What is a generator and how does yield work?
Reviewed by Gurusankar M.
β‘ Short Answer
A generator is a function that uses `yield` to produce values lazily, one at a time, pausing and resuming its state between calls. It doesn't build the whole result in memory, so it handles huge or infinite streams cheaply. Calling it returns a generator (an iterator) you loop over.
βCoffee Chat Question
Concept Made Simple
βWhat is a generator and how does yield work?β
π§ Mind Map Answer
Remember It Faster
β¨οΈHands-on Keyboard
Learn by Doing
def first_n(n):
i = 0
while i < n:
yield i # pause & resume here
i += 1
for x in first_n(3):
print(x)
total = sum(x * x for x in range(1_000_000)) # lazy, low memory
print(total)0 1 2 (large sum)
π₯What If?
Think Beyond the Expected
Why use a generator instead of returning a full list for a huge dataset?
A list materializes every element in memory at once; a generator yields one at a time, using near-constant memory β essential for large files, database cursors, or infinite streams. The trade-off: a generator is single-pass (consumed once) and has no len() or indexing.
πReal World
Streaming lines from a multi-GB file, paginating an API, or building data pipelines all use generators so memory stays flat regardless of data size β a core scalability tool in Python.
π―Interviewer's Expectation
Keywords they're listening for:
β οΈCommon Mistakes
- βTrying to reuse an exhausted generator
- βCalling len() or indexing a generator
- βBuilding a list when a generator would scale better
β Best Practices
- βUse generators for large/streaming data
- βUse generator expressions for one-pass pipelines
- βRemember they're single-use
πFollow-up Questions
- 1Generator vs list β memory and reuse trade-offs?
- 2What does `yield from` do?
- 3How are generators related to iterators?
π§©Related Technologies
Continue Learning with AI
Take this question deeper with your favourite AI assistant. Pick a depth, copy the prompt, or open it directly β AI is your learning companion, not a shortcut.
Plain-language foundations
I'm preparing for a software engineering interview and want to understand this from scratch, as a beginner. Topic: Generators (Python) Interview question: "What is a generator and how does yield work?" Please: 1. Explain the core idea in simple, plain language, using an everyday analogy. 2. Define any technical terms you use. 3. Walk through one small, concrete example. 4. Finish with a single sentence I can easily remember. Keep the tone friendly and assume I'm new to this topic.
Was this answer helpful?
β Featured Products
Support our platform by exploring our recommended products.
As an Amazon affiliate, purchases through these links may earn us a small commission β at no extra cost to you. It helps keep Full Stack Interview Guru free.