Medium👤 3-5 years👤 8-15 years 1 min read

What is a generator and how does yield work?

Asked inAmazonGoogleMicrosoftDeloitte
#generator#yield#lazy#memory#iterator
Report issue

⚡ 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

yieldproduce a value, pause, keep state
Lazycomputes on demand, item by item
MemoryO(1) — no full list built
Genexpr(x for x in xs) - inline generator

⌨️Hands-on Keyboard

Learn by Doing

python
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)
Output
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:

yield produces lazilykeeps state between callsconstant memorysingle-pass/consumed oncegenerator expression

⚠️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

iteratorsyield fromitertools

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.
Open inChatGPTGeminiClaude

Was this answer helpful?

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.

Related Questions